EF Code-First:具有单向导航的多对多

时间:2012-06-07 15:26:53

标签: c# entity-framework-4.1 ef-code-first

我正在尝试创建一个代码优先模型,其中一个人可以有很多喜欢的电影,但我不想在电影表中使用FK。

实现这一目标的唯一方法是让EF在两个实体之间创建一个链接表,为此(afaik)我在与Person有关的Movies实体上创建了一个集合属性...

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual IList<Movie> FavouriteMovies { get; set; }
}

public class Movie
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual IList<Person> People { get; set; } // I don't want this here :(
}

我希望电影看起来像这样......

public class Movie
{
    public int Id { get; set; }
    public string Name { get; set; }
}

但是在这样做时,EF不会创建链接表,它只会打击Movies表中的Person_Id FK列。

我不希望这种情况发生,因为电影不应该与人有任何关系,我可能想把它与其他东西联系起来。

那我怎么吃蛋糕吃呢?

1 个答案:

答案 0 :(得分:1)

它应该。你如何添加你的实体? 这是一个示例:

public class Character : BaseEntity
{
    public string Name { get; set; }
    public bool IsEvil { get; set; }
    public virtual ICollection<Videogame> Videogames { get; set; } 
}
public class Videogame : BaseEntity 
{
    public string Name { get; set; }
    public DateTime ReleasedDate { get; set; }
    public virtual ICollection<Character> Characters { get; set; }
    public Author Author { get; set; }
}

这是添加记录的地方:

[Test]
public void CreateJoinTable()
{
    var character = new Character() {Name = "Wario", IsEvil = true};
    var videogame = new Videogame() {Name = "Super Mario Bros 20", ReleasedDate = DateTime.Now , Characters = new Collection<Character>()};
    videogame.Characters.Add(character);
    var context = new NerdContext();
    context.Add(videogame);
    context.SaveAllChanges();
}

以下是代码段的来源:http://george2giga.com/2012/05/02/easy-join-tables-with-ef-code-first/