我正在尝试创建一个代码优先模型,其中一个人可以有很多喜欢的电影,但我不想在电影表中使用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列.
我不希望这种情况发生,因为电影不应该与人有任何关系,我可能想把它与其他东西联系起来.
那我怎么吃蛋糕吃呢?
解决方法
这应该.你如何添加你的实体?
这是一个示例:
这是一个示例:
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/
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。