【问题标题】:Entity Framework code first for object with collection of properties实体框架代码首先用于具有属性集合的对象
【发布时间】:2020-06-30 07:06:00
【问题描述】:

我将 C# 和 .NET Core 与 MySql 和 Entity Framework 一起使用。

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

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

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

在这种情况下,在数据库中,我应该有表 ProductsProperties(其中描述了属性,如名称和一些附加信息)和链接表 ProductProperties,存储产品 ID、属性 ID 和值.

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

如何先用代码实现它?

再创建一个实体 PropertyValue 并将其存储在 Product 下是否是一种好方法?

【问题讨论】:

  • 您的问题到底是什么?您无法创建表或关系或获取查询?
  • 看看 EAV。这就是您要查找的(反)模式的名称。
  • 你想要一个带有额外属性的多对多表吗?
  • @Vince 是的,没错。

标签: c# entity-framework .net-core ef-code-first code-first


【解决方案1】:

这样的东西应该给你一个一对多的关系,虽然你需要给 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,或者使用数据注释来完成相同的工作。

【讨论】:

    【解决方案2】:

    好的,创建一个这样的表:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-29
      • 2012-09-23
      • 1970-01-01
      相关资源
      最近更新 更多