首先是带有属性集合的对象的实体框架代码

问题描述 投票:0回答:2

我在MySql和Entity Framework中使用C#和.Net核心。

我有一个带有属性集合的对象。像这样:

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;}
}

在这种情况下,在数据库中,我应该具有表Products,Properties(其中描述了属性,如名称和一些其他信息),以及链接表ProductProperty,存储产品ID,属性ID和值。

但是我不知道如何使用代码优先方法来做到这一点。

我该如何先用代码实现它?这是再创建一个实体PropertyValue并将其存储在Product下的好方法吗?

c# entity-framework .net-core ef-code-first code-first
2个回答
0
投票

这样的事情应该给您带来一对多的关系,尽管您需要给Value提供一个类型,例如将其存储在数据库中的字符串,通常对于像这样的动态解决方案,您可能会添加一个类型来指定键入要反序列化的内容,但是由于您无论如何都要反序列化,因此您还可以将其作为json或在数据库中添加其他内容。

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;}
}

除非您要创建一个非常动态的系统,否则将属性作为表似乎并不正确,它取决于您所做的很多事情,如果这样,键值数据库可能是一个更好的工具您的主要问题是什么,就像大多数复杂的事情一样,这取决于。

此示例是一种基于约定的方法,这就是为什么必须确切地调用诸如ProductId之类的属性的原因。如果您想要更多地控制名称和关系等,或者使用数据批注来完成相同的工作,则可以查看EntityTypeConfigurations。


0
投票

确定创建一个这样的表:

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
}

如果使用的是EntityFramework Core,则还必须将其添加到数据库上下文中:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  modelBuilder.Entity<ProdcutProprties>().HasKey(x => new { x.ProductId , x.PropertyId });
}
© www.soinside.com 2019 - 2024. All rights reserved.