实体框架 CTP5,代码优先。帮助通过对象模型创建参考表

发布于 2024-10-11 00:32:30 字数 493 浏览 1 评论 0原文

我正在创建新模型,让 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

感情旳空白 2024-10-18 00:32:30

EF 认为 Model 和 Model 之间存在一对多关系。 Metal 和最简单的建模方法是将模型 ID 存储在 Metal 表中。
如果您想保持 Metal 表“干净”(即没有关系数据),那么关系数据必须存储在单独的表中,但这样做也会隐式更改 Model 和 Metal 之间的关系。金属。
如果您确实想完成此操作,那么您可以告诉 EF 您希望 Model 和 Model 之间建立单向多对多的关系。金属。
您可以在 DbContext 的 OnModelCreating 函数中执行此操作。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Model>().HasMany(o => o.Metals).WithMany();
}

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.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Model>().HasMany(o => o.Metals).WithMany();
}
策马西风 2024-10-18 00:32:30

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文