ASP.NET MVC实体框架codeFirst多对多(CRUD) [英] ASP.NET MVC Entity Framework CodeFirst Many To Many (CRUD)

查看:129
本文介绍了ASP.NET MVC实体框架codeFirst多对多(CRUD)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个问题,但我要开始第一个和最小的。我有两个型号,一个多对多的关系,类和项目。在每个模型我有其他模型的ICollection的。我初始化集合作为一个新的HashSet()为项目的构造,反之亦然的范畴。我在网上看了,这将在数据库中创建一个新表,每个模型作为新表的PK的PK。我的自定义命名他们和诸如此类的东西,通过流利的API,但你的想法。

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.

此制定出很大的。所以,我让我的控制器和创建和使用脚手架创建CRUD意见。我创建了一个几类..大。现在,当我去创造一个新的项目,我想它是什么,证明我是previously创建的类别列表,并至少有一个需要通过项目推动之前选择。该视图显示没有类别在所有选择,并允许它通过为空。我知道如何使需要属性,但我不知道如何使所需的集合属性,并抓住所有的类别从数据库到Project present创建视图选择....

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

推荐答案

尝试:

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

您的查询code里面,

inside your query code,

您将需要

using System.Data.Entity;

要获得包括法

这篇关于ASP.NET MVC实体框架codeFirst多对多(CRUD)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆