I am working on school project which is about showing some database properties that I learned.I have 2 entity classes called Person and CarInformation.I want to show Name, Location,WhishedDays from Person and Brand, PlateNumber from CarInformation,together.
I tried generating new class called then I grouped Name, Location, WishedDays,Brand,PlateNumber.In the corresponding controller, I made a List with Select function but failed.
CarInformation Entity Class
public int Id { get; set; } //Primary key of carinfo table
public string Brand{ get; set; }
public string PlateNumber { get; set; }
public int Milage { get; set; }
public string InsuranceCompany{ get; set; }
public double ConsumptionPerMile { get; set; }
public int DailyPrice { get; set; }
public DateTime AvailableDates { get; set; }
[ForeignKey("Persons")]
public int OwnerId { get; set; } //foregein key (Person table to carinfo table)
public virtual Person Persons { get; set; } //Navigation property
public List<Sales> Sales { get; set; }
Person Entity Class
public int Id { get; set; } //primary key of person table
public string Name { get; set; }
public string Location { get; set; }
public int WishedDays { get; set; }
public virtual CarInformation Cars { get; set; } //Navigation property
public List<CarInformation> cars { get; set; } //bir insana ait birden fazla araba olabilir
public List<Sales> sales { get; set; }
Person-CarInformation Class
public string Name { get; set; }
public string Location { get; set; }
public int WishedDays { get; set; }
public string Brand { get; set; }
public string PlateNumber { get; set; }
Corresponding controller`s Index Method
public ActionResult Index()
{
var isimler = db.People.
Select(i => new Person_CarInformation() { Location=i.Location,Name=i.Name, Brand=i.Cars.Brand,PlateNumber=i.Cars.PlateNumber});
return View(isimler.ToList());
}
When I execute in this circumstances I get this result
Brand and PlateNumber is empty.
Any advises?
Thank You.
https://imgur.com/D9a8whD
You haven't included dependent entity while fetching data. You can get it by changing your code like shown below.
var isimler = db.People.Include("Cars").
Select(i => new Person_CarInformation() { Location=i.Location,Name=i.Name, Brand=i.Cars.Brand,PlateNumber=i.Cars.PlateNumber});
Related
I have a question. I created a table with many to many relationships as below. What code should I write so that I can enter multiple categories when adding a product to the database?
I would be glad if you explain with an example.
For example, I can enter product.name information with the name information I received from the user, but I do not know how to save data in the relevant tables.
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public List<ProductCategory> ProductCategories { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public double? Price { get; set; }
public string Description { get; set; }
public string ImageUrl { get; set; }
public bool IsApproved { get; set; }
public bool IsHome { get; set; }
public List<ProductCategory> ProductCategories { get; set; }
}
public class ProductCategory
{
public int CategoryId { get; set; }
public Category Category { get; set; }
public int ProductId { get; set; }
public Product Product { get; set; }
}
You can insert them by the join table like this:
var product = new Product { Name = "AA" };
var categories = new List<Category>
{
new Category{ Name = "a"},
new Category{ Name = "b"},
new Category{ Name = "c"},
};
foreach (var category in categories)
{
_context.ProductCategory.Add(
new ProductCategory
{
Product = product,
Category = category
});
}
_context.SaveChanges();
I am not sure which version you are using. with EF Core 5.o find an example at https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-5.0/whatsnew
Models:
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public ICollection<Product> Products { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public double? Price { get; set; }
public string Description { get; set; }
public string ImageUrl { get; set; }
public bool IsApproved { get; set; }
public bool IsHome { get; set; }
public ICollection<Category> Categories { get; set; }
}
Or If you are using EE 6 or EF Core 3.1 then your models should be like:
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public ICollection<Product> Products { get; set; }
public ProductCategory ProductCategorie { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public double? Price { get; set; }
public string Description { get; set; }
public string ImageUrl { get; set; }
public bool IsApproved { get; set; }
public bool IsHome { get; set; }
public ICollection<Category> Categories { get; set; }
public ProductCategory ProductCategorie { get; set; }
}
public class ProductCategory
{
public int CategoryId { get; set; }
public Category Category { get; set; }
public int ProductId { get; set; }
public Product Product { get; set; }
}
For inserting data to Many-Many tables: https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/complex-data-model?view=aspnetcore-5.0
then please look at the section:Seed database with test data
I have two entities Team, MainEntry. Now I want to get all team details in dropdown while entring in MainEntry view
in MVC.
In other word in the MainEntry views I want get all team details in the dropdown.
Im using VS-2015, MVC5, EF6 with Code first migration.
public class Team
{
public int TeamId { get; set; }
public string TeamName { get; set; }
public string TeamAge { get; set; }
public string TeamLocation { get; set; }
}
public class MainEntry
{
public int MainEntryId { get; set; }
public string TeamAssignment { get; set; }
public string Role { get; set; }
public string Series { get; set; }
public string Stock { get; set; }
public string Points { get; set; }
public sting Teamname {get; set;} //(dropdown fill)
public string Teamage {get;set;} //(dropwon fill)
public string TeamLocation {get;set;} //(dropwon fill)
}
You can populate your dropdown list like
ViewBag.Teamnames = _db.Team.Select(c => new SelectListItem
{
Text = c.Teamname ,
Value = c.MainEntryId.ToString(),
Selected = true
});
and in your view:
#Html.DropDownList(
"TeamName",
(IEnumerable<SelectListItem>)ViewBag.Teamnames,
new { style = "max-width: 600px;" }
)
Another way
I usually create a view model that contains both the model if you want collection in model you can change your model as below and update your migration configuration file
public class MainEntry {
public int MainEntryId { get; set; }
public string TeamAssignment { get; set; }
public string Role { get; set; }
public string Series { get; set; }
public string Stock { get; set; }
public string Points { get; set; }
public IEnumerable<Team> Teamname { get; set; }//(dropwon fill)
public IEnumerable<Team> Teamage //(dropwon fill)
public IEnumerable<Team> TeamLocation //(dropwon fill) }
I have two models and for which I will create tables through migration and database update. My first model is named Service, and it consists of these fields:
public class Service
{
public int ServiceID { get; set; }
public string ServiceType { get; set; }
public string Category { get; set; }
public string Subcategory { get; set; }
public int Count { get; set; }
}
My second model is called Business, and it has the following fields:
public class Business
{
public int BusinessID { get; set; }
public string BusinessName { get; set; }
public string BusinessWebsite { get; set; }
public string BusinessAddress { get; set; }
public string BusinessCity { get; set; }
public string BusinessState { get; set; }
public string BusinessZip { get; set; }
public string BusinessDescription { get; set; }
[Range(0.0, 5.0)]
public int Rating { get; set; }
public DateTime LastLogIn { get; set; }
// Need to add more fields
}
The point is that I want to add Category and Subcategory fields into my Business model, but the values of Category and Subcategory fields, should be one of the values inside the Service table's values for Category and Subcategory.
Simply, I want to connect those two fields. How can I achieve it? Should I just put a Service property inside the Business model?
Break out a separate entity for "Category" and then use foreign keys:
public class Category
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class Service
{
...
public virtual Category Category { get; set; }
public virtual Category Subcategory { get; set; }
}
// Do the same when adding category/subcategory fields to `Business`
If you want to ensure that these categories are only tied to Service (and you potentially have other types of categories or something) you can always just make the entity ServiceCategory or something and only create a relationship to it from Service.
You need to separate your break out your database to store lookup table for category and a lookup table for subcategory.
Then you can create:
public class Category {
public int CategoryId { get; set; }
public string Name { get; set; }
}
public class SubCategory {
public int SubCategoryId { get; set; }
public string Name { get; set; }
}
Then change your service class to:
public class Service
{
public int ServiceID { get; set; }
public string ServiceType { get; set; }
public int CategoryId { get; set; }
public int SubcategoryId { get; set; }
public int Count { get; set; }
}
and change your Business class to:
public class Business
{
public int BusinessID { get; set; }
public string BusinessName { get; set; }
public string BusinessWebsite { get; set; }
public string BusinessAddress { get; set; }
public string BusinessCity { get; set; }
public string BusinessState { get; set; }
public string BusinessZip { get; set; }
public string BusinessDescription { get; set; }
public int CategoryId { get; set; }
public int SubCategoryId { get; set; }
[Range(0.0, 5.0)]
public int Rating { get; set; }
public DateTime LastLogIn { get; set; }
// Need to add more fields
}
All,
I need to add a domain class for a new key table that relates a table of club members ([dbo].NewClubProspect) to emails ([dbo].NewClubEmail) sent to them.
I am not sure how to set this up in the domain classes.
Question
Need to annotate the key table (NewClubProspectNewClubEmail) Since both properties are foreign keys, not sure if I need an actual primary key, too? How do I annotate this?
Here is a diagram of how the tables relate. The table on the bottom of the diagram (NewClubProspectNewClubEmail) is the new table that I need to create in the database and in code, in a domain class.
Here are my domain classes (chopped down for brevity)
public class NewClub
{
public NewClub()
{
NewClubProspects = new List<NewClubProspect>();
NewClubEmails = new List<NewClubEmail>();
}
public int Id { get; set; }
public string NewClubName { get; set; }
public string NewClubLocation { get; set; }
public string NewClubType { get; set; }
public string NewClubCity { get; set; }
public string NewClubState { get; set; }
public string NewClubCountry { get; set; }
public virtual List<NewClubProspect> NewClubProspects { get; set; }
public virtual List<NewClubEmail> NewClubEmails { get; set; }
}
public class NewClubProspect
{
[Key]
public int Id { get; set; }
//Foreign Key
public int NewClubId { get; set; }
public bool IsConverted { get; set; }
public string ProspectFirstName { get; set; }
public string ProspectLastName { get; set; }
public string ProspectEmail { get; set; }
public virtual NewClub NewClub { get; set; }
public virtual List<NewClubEmail> NewClubEmails { get; set; }
}
public class NewClubEmail
{
//Primary key
[Key]
public int Id { get; set; }
//Foreign Key
public int NewClubId { get; set; }
public string Subject { get; set; }
public virtual List<NewClubProspect> Recipients { get; set; }
public string Body { get; set; }
public DateTime CreateDate { get; set; }
public DateTime ModifiedDate { get; set; }
public DateTime? SentDate { get; set; }
public NewClub NewClub { get; set; }
public NewClubEmail()
{
Recipients = new Collection<NewClubProspect>();
}
}
//---------------------------------------------------------
// Not sure what to do here. They are both foreign keys
//---------------------------------------------------------
public class NewClubProspectNewClubEmail
{
public int NewClubEmail_Id {get; set;}
public int NewClubProspect_Id {get; set;
}
Just mark both as Key:
[Key]
public int NewClubEmail_Id {get; set;}
[Key]
public int NewClubProspect_Id {get; set;}
I have a database with 3 tables:
Subjects
Members
Topics
Then I added the connection string to web.config and created an EF with the following classes:
namespace MySite.Models
{
public class MySiteDBModel : DbContext
{
public DbSet<Topic> Topics { get; set; }
public DbSet<Subject> Subjects { get; set; }
public DbSet<Member> Members { get; set; }
public DbSet<TopicDataModel> TopicDataModel { get; set; }
protected override void OnModelCreating(DbModelBuilder mb)
{
mb.Conventions.Remove<PluralizingTableNameConvention>();
}
}
public class Topic
{
[Key]
public int TopicID { get; set; }
public int SubID { get; set; }
public int MemberID { get; set; }
public string TDate { get; set; }
public string Title { get; set; }
public string FileName { get; set; }
public int Displays { get; set; }
public string Description { get; set; }
public virtual Subject Subject { get; set; }
public virtual Member Member { get; set; }
public virtual ICollection<TopicView> TopicView { get; set; }
}
public class Subject
{
[Key]
public int SubID { get; set; }
public string SubName { get; set; }
public virtual ICollection<Topic> Topic { get; set; }
}
public class Member
{
[Key]
public int MemberID { get; set; }
public string FLName { get; set; }
public string Email { get; set; }
public string Pwd { get; set; }
public string About { get; set; }
public string Photo { get; set; }
public virtual ICollection<Topic> Topic { get; set; }
}
public class TopicDataModel
{
[Key]
public int TopicID { get; set; }
public string SubName { get; set; }
public string FLName { get; set; }
public string TDate { get; set; }
public string Title { get; set; }
public int Displays { get; set; }
public string Description { get; set; }
}
}
Now when I am trying to query the database with the this code:
public ActionResult Index()
{
var topics = from t in db.Topics
join s in db.Subjects on t.SubID equals s.SubID
join m in db.Members on t.MemberID equals m.MemberID
select new TopicDataModel()
{
TopicID = t.TopicID,
SubName = s.SubName,
FLName = m.FLName,
TDate = t.TDate,
Title = t.Title,
Displays = t.Displays,
Description = t.Description
};
return View(topics.ToList());
}
I got this Error:
The model backing the 'MySiteDBModel' context has changed since the
database was created. Either manually delete/update the database, or
call Database.SetInitializer with an IDatabaseInitializer instance.
For example, the DropCreateDatabaseIfModelChanges strategy will
automatically delete and recreate the database, and optionally seed it
with new data.
Please help me!!!!!!
You need to set some controls on how EF is handling changes to your data model. Julie Lerman has a good blog post on Turning Off Code First Database Initialization Completely.
Also, here is a good overview - Inside Code First Database Initialization