简体   繁体   中英

Creating relationship between two tables using Entity Framework

I am working on some CRUD methods for a web app. I am using Entity Framework with SQL Server 2008. In particular, I have two tables that are linked using a cross reference table. It's in the following format:

  • Table Tbl_Plan
    • PlanId
    • PlanNm
    • Active
  • Table Tbl_Person
    • PersonId
    • PersonNm
    • PersonData
  • Xref table 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. 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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM