ASP.NET MVC Entity Framework CodeFirst Many To Many (CRUD)

流过昼夜 提交于 2019-12-23 03:18:32

问题


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....


回答1:


Try :

Context.Project.Include(p=>p.Category)

inside your query code,

you will need

using System.Data.Entity;

to get the include method




回答2:


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.



来源:https://stackoverflow.com/questions/9104880/asp-net-mvc-entity-framework-codefirst-many-to-many-crud

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!