[英]Creating relationship between two tables using Entity Framework
I am working on some CRUD methods for a web app.我正在为 web 应用程序研究一些 CRUD 方法。 I am using Entity Framework with SQL Server 2008. In particular, I have two tables that are linked using a cross reference table.
我正在使用带有 SQL Server 2008 的实体框架。特别是,我有两个使用交叉引用表链接的表。 It's in the following format:
它采用以下格式:
Tbl_Plan
Tbl_Plan
PlanId
PlanNm
Active
Tbl_Person
Tbl_Person
PersonId
PersonNm
PersonData
Xref_PersonPlan
Xref_PersonPlan
PersonId
PersonNm
Now, when I am creating a new plan I have been trying to link the two together.现在,当我创建一个新计划时,我一直试图将两者联系在一起。 I'm not sure how.
我不确定如何。 I know it has something to do with referencing the relationship or creating it.
我知道这与引用关系或创建关系有关。
The tables are set up correctly, because I can pull the data just fine once it's created (ie my sample entries in SQL Server) but creating the reference is where I am stumped.表格设置正确,因为我可以在创建数据后很好地提取数据(即我在 SQL 服务器中的示例条目),但创建引用是我难过的地方。 I tried the following:
我尝试了以下方法:
using (Entities context = new Entities())
{
// TblPlan plan has already been instantiated
plan.TblPersons.Add(person);
context.AddToTblPlans(plan);
context.SaveChanges();
But obviously, the .Add()
isn't what I'm looking for....help?但显然,
.Add()
不是我要找的......帮助?
The short answer is that many-to-many relationships are not supported in LINQ to SQL the same way they are in Entity Framework and other ORMs, and you'll have to implement the desired behavior yourself.简短的回答是 LINQ 到 SQL 不支持多对多关系,就像它们在实体框架和其他 ORM 中一样,您必须自己实现所需的行为。
Take a look at this article.看看这篇文章。 It describes an approach that should work for you.
它描述了一种适合您的方法。
Someone just pointed me in the right direction.有人刚刚为我指出了正确的方向。 I should have waited ten more minutes.
我应该再等十分钟。 I was missing the.AttachTo() - I needed to attach the reference to the context before adding, since it was throwing an InvalidArgumentException.
我错过了 .AttachTo() - 我需要在添加之前将引用附加到上下文,因为它抛出了 InvalidArgumentException。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.