一对多关系实体框架4.1 mvc的问题
我有这些模型:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Books> FavoriteBooks { get; set; }
}
public class Books
{
public int Id { get; set; }
public string Title { get; set; }
public string Author{ get; set; }
}
当我运行 DBContext 并检查生成的表时,Books 表已创建 Student_Id 列。我希望图书表只是一个参考,而不是链接回学生。 如何使这种关系成为单向关系并且不会在 Books 中创建 Student_Id 列?我可以使用 Fluent-api 吗?或者仅在简单的数据注释中?
谢谢
i have these models:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Books> FavoriteBooks { get; set; }
}
public class Books
{
public int Id { get; set; }
public string Title { get; set; }
public string Author{ get; set; }
}
When i run DBContext and check the generated tables, the Books table have created Student_Id column. I want the Books table to be just a reference and not linked back to Student.
How can I make this relationship uni-directional and will have no Student_Id column created in Books? can i use fluent-api? or in simple data annotations only?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 Fluent API 中,它应该看起来像这样:
这将为您创建一个“StudentBooks”表来维护多对多关系。这不是您的问题所暗示的一对多关系,因为一个学生可以有很多最喜欢的书,但每本书可能是许多学生最喜欢的。
更新
为了完整起见,如果您已经定义了该链接表并且需要告诉 EF 映射是什么样子,则可以执行以下操作:
In the fluent API it should look something like this:
That'll create a "StudentBooks" table for you to maintain the many-to-many relationship. It's not a one-to-many relationship as your question suggests, since a student can have many favourite books, but each book might be a favourite of many students.
Update
For the sake of completeness, here's how you'd do it if you already have that linking table defined and need to tell EF what the mapping looks like: