![](/img/trans.png)
[英]How to map non-public Collection properties with Entity Framework Code First?
[英]Entity Framework code first for object with collection of properties
我在 MySql 和实体框架中使用 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;}
}
在这种情况下,在 DB 中,我应该有表 Products、Properties(其中描述了属性,如名称和一些附加信息)和链接表 ProductProperties,存储产品 Id、property Id 和值。
但我无法弄清楚如何使用代码优先方法来做到这一点。
我怎么能先用代码实现它? 创建另一个实体 PropertyValue 并将其存储在 Product 下是一种好方法吗?
像这样的东西应该给你一个 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。
好的,创建一个这样的表:
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 });
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.