实体框架 CTP5,代码优先。帮助通过对象模型创建参考表
我正在创建新模型,让 EF 为其生成数据库。模型如下所示:
public class Model
{
public int Id { get; set; }
public string StyleNumber { get; set; }
public virtual IList<Metal> Metals { get; set; }
public virtual IList<ModelImage> Images { get; set; }
}
public class Metal
{
public int Id { get; set; }
public string Description { get; set; }
}
我希望 Metal 成为带有两列的参考表,“描述”字段是唯一的。相反,EF 创建带有引用模型 ID 的附加列的 Metal 表。是否有一种简单的方法可以通过数据注释或 Fluid API 来更改行为?
I'm creating new models that I will let EF generate the database for. Models looks like this:
public class Model
{
public int Id { get; set; }
public string StyleNumber { get; set; }
public virtual IList<Metal> Metals { get; set; }
public virtual IList<ModelImage> Images { get; set; }
}
public class Metal
{
public int Id { get; set; }
public string Description { get; set; }
}
I would like Metal to be a reference table w/ the two columns, the "Description" field being unique. Instead, EF creates the Metal table with an additional column referencing the Model Id. Is there a simple way to change the behavior via data annotations or the fluid API?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
EF 认为 Model 和 Model 之间存在一对多关系。 Metal 和最简单的建模方法是将模型 ID 存储在 Metal 表中。
如果您想保持 Metal 表“干净”(即没有关系数据),那么关系数据必须存储在单独的表中,但这样做也会隐式更改 Model 和 Metal 之间的关系。金属。
如果您确实想完成此操作,那么您可以告诉 EF 您希望 Model 和 Model 之间建立单向多对多的关系。金属。
您可以在 DbContext 的 OnModelCreating 函数中执行此操作。
EF thinks you're having a one-to-many relationship between Model & Metal and the simplest way to model that is by storing the Model ID in the Metal table.
If you want to keep the Metal table 'clean' (i.e. no relationship data), then the relationship data must be stored in a seperate table, but by doing that you're also implicitly changing the relationship between Model & Metal.
If you really want to go through with this, than you can tell EF that you want a one-way-many-to-many relationship between Model & Metal.
You can do that like this inside the DbContext's OnModelCreating function.
Steven K 的答案对于删除 Metal 表上的外键条目是正确的,但是它不会强制说明字段的唯一要求。但这不是他的错,因为不幸的是,EF Code First 还没有唯一的约束注释。
Steven K's answer is correct for removing the foreign key entry on the Metal table, however it will not enforce Unique requirement for the Desctiption field. That is not his fault though because, unfortunately, EF Code First does not have a unique constraint annotation yet.