2012-12-20 45 views
0

我有有几个其他表一个一对多的关系的表的EF代码优先模式:表与几个一个一对多的关系

public class Note 
{ 
    [Key] 
    public Guid Id { get; set; } 
    public string NoteText { get; set; } 
    public string Author { get; set; } 
    public DateTime? CreationDate { get; set; } 
} 

public class Foo 
{ 
    public Foo() 
    { 
    Notes = new HashSet<Note>(); 
    } 

    [Key] 
    public Guid Id { get; set; } 
    public virtual ICollection<Note> Notes { get; set; } 
    // other properties ommited... 
} 

public class Bar 
{ 
    public Bar() 
    { 
    Notes = new HashSet<Note>(); 
    } 

    [Key] 
    public Guid Id { get; set; } 
    public virtual ICollection<Note> Notes { get; set; } 
    // other properties ommited... 
} 

正如你所看到的,FooBar有自己的Notes名单,但Note属于无论是Foo一个Bar

脚手架迁移时,EF为Notes表中的FooBar创建一个外键,我认为这是不正确的。相反,我希望在FooNotes之间创建链接表,并在BarNotes之间创建链接表。

有没有办法自动做到这一点?或者我必须在我的代码优先实现中手动创建这些类?

回答

0

这已经在这other post回答! 但为了节省你一点点谷歌搜索,你正在得到一个一对多的关联,这是正确的。你要多到许多在你的代码的关系,所以你需要做的是:

在Notes

类:

public class Note 
{ 
    [Key] 
    public Guid Id { get; set; } 
    public string NoteText { get; set; } 
    public string Author { get; set; } 
    public DateTime? CreationDate { get; set; } 
    public DateTime? CreationDate { get; set; } 
    public virtual ICollection<Foo> Foos { get; set; } 
    public virtual ICollection<Bar> Bars { get; set; } 
} 

希望这有助于

+0

我真的想要一个单因为票据只属于一个Foo(或Bar),而Foo(或Bar)可以有多个票据。另外,我不需要Notes的导航属性。你有另外一个建议吗? –

+1

你可以试试[此链接](http://weblogs.asp.net/manavi/archive/2011/05/17/associations-in-ef-4-1-code-first-part-6-many-valued -associations.aspx),您需要使用'.WithMany'函数或'.Map'以及'EntityTypeConfiguration'。该链接有有用的信息。我还没有看到任何使用注释来做到这一点的方法。 – Toze