简体   繁体   中英

Entity Framework code first for object with collection of properties

I'm using C# and .Net core with MySql and Entity Framework.

I have an object with a collection of properties. Like this:

public class Product
{
  public int Id {get; set;}
  public string Name{get; set;}
  public IEnumarable<Property> Properties{get; set;}
}

public class Property
{
  public int Id {get; set;}
  public string Name{get; set;}
  public object Value{get; set;}
}

In this case in the DB I should have tables Products, Properties(where property is described, like name and some additional info), and link table ProductProperties, storing product Id, proeprty Id and Value.

But I can't figure out how to do this with Code first approach.

How could I implement it with code first? Is it a good way to create one more entity PropertyValue and store it under Product?

Something like this should give you a 1-to-many relationship, although you need to give Value a type, like string to store it in the database, often for dynamic solutions like this you would then maybe add a type to specify the type to deserialize into, but since you then deserialize anyway you could also just add things as json or something else in the db.

public class Product
{
  public int Id {get; set;}
  public string Name{get; set;}
  public ICollection<Property> Properties{get; set;}
}

public class Property
{
  public int Id {get; set;}
  public string Name {get; set;}
  public string Value {get; set;}
  public int ProductId {get; set;}
}

Unless you are making a very dynamic system, it doesn't seem right to have the properties as a table, depends a lot of what you are making, and maybe key-value db might be a better tool for the job if thats what your main problem is, as with most complicated things, it depends.

This example is a convention based approach, which is why properties like ProductId have to be called exactly that. You can look at EntityTypeConfigurations if you want more control of names and relationships and such, or use data annotations to achieve the same job.

Ok so create a table like this:

public class ProductProprties
{
  public int ProductId {get; set;}
  public Product Product {get;set;}
  public int PropertyId {get; set;}
  public Property Property {get;set;}      
  //other props
}

If you are using EntityFramework Core, then you have to add this to your databse context as well:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  modelBuilder.Entity<ProdcutProprties>().HasKey(x => new { x.ProductId , x.PropertyId });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM