Solved

Entity Framework doesn't update Many to Many relation

Posted on 2013-06-18
10
460 Views
Last Modified: 2013-06-20
Hi Experts,

I have the following tables in an SQL2008 database:

Accommodation
code	varchar(18)
name	varchar(80)

Open in new window

This table has more columns but i have removed them here for simplicity.

Attributes
code	int
name	varchar(50)

Open in new window

     
AccommodationAttributes
AccommodationCode	varchar(18)
AttributeCode	int

Open in new window


As you may get, AccommodationAttributes describes the many to many relationship between Accommodations and Attributes.

I have created my model (EF5) using database first, and it has created two classes linked with a navigation property.

All this seems correct.

What i am trying to do is add values in the db, but though i am able to add Accommodations and Attributes, i don't seem to be able to make it add the corresponding values in the AccommodationAttributes table.

I am reading from an XML file.
Bellow is a code sample of what i am trying to do.

var Accommodations = from a in xe.Elements("accommodation") select a;
foreach (var accommodation in Accommodations)
{
   var AccCode = accommodation.Element("code").Value;
   Accommodation a = context.Accommodations.Where(x=>x.code == AccCode).SingleOrDefault();
   bool newAccommodation = a == null ? true : false;
   a = !newAccommodation ? a :
      new Accommodation
      {
          code = accommodation.Element("code") == null ? null : accommodation.Element("code").Value,
          name = accommodation.Element("name") == null ? null : accommodation.Element("name").Value
      };
      foreach (var attribute in accommodation.Elements("attributes").Elements("attribute").Select(x=>x.Value))
      {
         Attribute at = context.Attributes.Where(x => x.name == attribute).SingleOrDefault();
         a.Attributes.Add(at);
      }
      context.SaveChanges();
}

Open in new window


After running this code i Run the following in SQL:
select COUNT(*) from Accommodations
select COUNT(*)from Attributes
select COUNT(*)from AccommodationAttributes

Open in new window


But though i see entries in the two tables, the link table comes with 0 rows.

I have tried other variations, like attaching the objects to the context, or implicitly specifying that it is a modified object.

By the time that this code will run i am sure that the Attributes are allready inserted in the db, but the Accommodation is either an Insert or Update.

I am eager to hear your thoughts,

Giannis
0
Comment
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
10 Comments
 
LVL 15

Accepted Solution

by:
jorge_toriz earned 500 total points
ID: 39260422
I did it with this code and everything worked so fine :s

EFModel.ExpertsExchangeEntities db = new EFModel.ExpertsExchangeEntities();
EFModel.Accommodation myAccommodation = new EFModel.Accommodation();
myAccommodation.Code = "Acc01";
myAccommodation.Name = "Accommodation 01";

myAccommodation.Attributes.Add(new EFModel.Attribute()
{
    Code = 1,
    Name = "Attribute 1"
});

myAccommodation.Attributes.Add(new EFModel.Attribute()
{
    Code = 2,
    Name = "Attribute 2"
});

db.AddToAccommodations(myAccommodation);

db.SaveChanges();

Open in new window

0
 
LVL 23

Author Comment

by:Ioannis Paraskevopoulos
ID: 39260517
Hi,

Thanks for the response...
Can you please elaborate a little bit?

Is db the context in my example?
I don't have a method AddToAccommodations.

Giannis
0
 
LVL 15

Expert Comment

by:jorge_toriz
ID: 39260566
your "context" variable is my "db" variable, the method AddToAccommodations was generated by the Entity Framework wizard.

I'm attaching the project in this reply.

I renamed the file EFModel\EE.edmx to EFModel\EE.txt to be able to send you the project in the zip, just fix the extension and the project should run without problems.
Project.zip
0
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
LVL 23

Author Comment

by:Ioannis Paraskevopoulos
ID: 39260680
Hi,

I do see that in your project. One question, is that EF4? I am using EF5.

Giannis
0
 
LVL 15

Expert Comment

by:jorge_toriz
ID: 39261130
Yes, I'm working with 4 :s
0
 
LVL 23

Author Comment

by:Ioannis Paraskevopoulos
ID: 39261693
Is it possible that EF4 is somewhat different from EF5 in that manner?
0
 
LVL 15

Expert Comment

by:jorge_toriz
ID: 39262797
I'm really sorry pal, I haven't worked on EF5, but let me search something about many to may relationships in EF5 and verify if there is something different that you must take care of
0
 
LVL 23

Author Comment

by:Ioannis Paraskevopoulos
ID: 39263580
Hi,

After further investigation, it seems that it works when i add a new Accommodation, but it fails when the Accommodation is already in the db and i just add new attributes. In my case in the process of developing i had first added the Accommodation and in a later step of development i created the process to import attributes. So i need to find a way to update the relationship when both accommodation and  attribute are already in the db. Thanks for the help.

Giannis
0
 
LVL 23

Author Comment

by:Ioannis Paraskevopoulos
ID: 39263680
I found the solution...The problem was i had set the AutoDetectChangesEnabled to False. When i commented out this line it worked. I am marking the answer as accepted because it was correct in its core and the expert could not know my settings due to information provided.

Thanks a lot for the help, even indirectly it helped me get the solution i needed.

Giannis
0
 
LVL 23

Author Closing Comment

by:Ioannis Paraskevopoulos
ID: 39263701
Thanks a lot for your help and patience.

Giannis
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…

635 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question