ASP.NET MVC 实体框架 CodeFirst 多对多 (CRUD)
我遇到了一些问题,但我将从第一个也是最小的问题开始。我有两个具有多对关系的模型:类别和项目。在每个模型中,我都有另一个模型的 ICollection。我将集合初始化为项目构造函数的新 HashSet(),对于类别反之亦然。我在网上读到这将在您的数据库中创建一个新表,其中每个模型的 PK 作为新表中的 PK。我通过 Fluent API 自定义了它们的名称,但你明白了。
这效果很好。因此,我制作了控制器并创建并使用脚手架来创建 CRUD 视图。我创建了几个类别..太棒了。现在,当我开始创建一个新项目时,我想要的是它向我显示之前创建的类别列表,并要求在推进项目之前至少选择一个类别。该视图根本不显示任何可供选择的类别,并允许其作为空进行遍历。我知道如何使属性成为必需的,但我不知道如何使集合属性成为必需的,并从数据库中获取所有类别以显示在项目创建视图中以供选择......
I have a few problems but I'm going to start with the first and smallest. I have two models with a many-many relationship, Category and Project. In each model I have an ICollection of the other model. I initialize the collection as a new HashSet() for the Project constructor and vice-versa for the Category. I've read online that this will create a new table in your database with the PK of each model as the PK in the new table. I custom named them and whatnot through Fluent API but you get the idea.
This worked out great. So I make my Controllers and create and use scaffolding to create the CRUD views. I create a few categories.. Great. Now when I get to creating a a new Project, what I want is it to show me a list of the Categories I previously created, and to require at least one be selected before pushing through the Project. The view shows no categories to select at all and allows it to go through as null. I know how to make a property required but I don't know how to make a collection property required and grab all of the categories from the database to present in the Project create view for selecting....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试:
在查询代码中,
您将需要
获取 include 方法
Try :
inside your query code,
you will need
to get the include method
为了启用延迟加载,您还需要将属性标记为“虚拟”;否则,您始终必须使用 .Include() 方法预先加载它们。
For enabling lazy load, you will also need to mark your properties as "virtual"; otherwise, you will always have to eager load them using the .Include() method.