C# 实体框架CTP5,代码优先。帮助通过对象模型创建引用表

C# 实体框架CTP5,代码优先。帮助通过对象模型创建引用表,c#,entity-framework,code-first,ef-code-first,entity-framework-ctp5,C#,Entity Framework,Code First,Ef Code First,Entity Framework 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; }

我正在创建新的模型,我将让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; }
}
公共类模型
{
公共int Id{get;set;}
公共字符串StyleNumber{get;set;}
公共虚拟IList{get;set;}
公共虚拟IList映像{get;set;}
}
公共级金属
{
公共int Id{get;set;}
公共字符串说明{get;set;}
}

我希望Metal是一个包含两列的参考表,“Description”字段是唯一的。相反,EF会创建一个金属表,其中包含一个引用模型Id的附加列。是否有一种通过数据注释或流体API更改行为的简单方法?

EF认为模型和金属之间存在一对多关系,最简单的建模方法是将模型Id存储在金属表中。 如果希望保持金属表“干净”(即没有关系数据),则关系数据必须存储在单独的表中,但这样做也会隐式更改模型与金属之间的关系。 如果你真的想这样做,你可以告诉EF,你想在模型和金属之间建立一种单向多对多的关系。 可以在DbContext的OnModelCreating函数中这样做

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Model>().HasMany(o => o.Metals).WithMany();
}
模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder)
{
modelBuilder.Entity().HasMany(o=>o.Metals).WithMany();
}

Steven K的答案对于删除金属表上的外键条目是正确的,但是它不会强制要求对Desctiption字段执行唯一的要求。但这不是他的错,因为,不幸的是,EF代码First还没有唯一的约束注释