Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework adds new record for navigation property

I have two entities, defined as following

public class Corporation
{
    public int Id{get;set;}
    public string Name{get;set;}
    public List<Location> Locations{get;set;} // All locations under this corp
}

public class Location
{
    public int Id{get;set;}
    public Corporation Corporation{get;set;} // Corporation is required in configuraion
}

When I try to add a Corporation and then a location, I get two Corporation defined. One by my function that adds Corporation(which is fine), and one by the function that adds location(which is the issue).

Location adding function is like this:

public void AddLocation(int locationId)
{
     using (Context context = new Context())
     {
          Location location = new Location();
          location.Corporation = GetCorporationFromDb(corpId);

          context.Locations.Add(location); // This one adds another same Corporation to DB
          context.SaveChanges();
     }
}

How can I avoid this? I have to add Corporation before Location because in the implementation Location calculates an electronic code using Corporation's database Id.

like image 953
Mert Akcakaya Avatar asked Nov 05 '25 03:11

Mert Akcakaya


1 Answers

This happens if you fetch the corporation from a different data context than the one you use to add the location. Try:

Context context = new Context();
Location location = new Location();
Corporation corporation = context.Corporations
    .Where(x => x.Id == corpId)
    .First();
location.Corporation = corporation;

context.Locations.Add(location);
context.SaveChanges();

This way, you use the same context for retrieving the Corporation and adding the Location.

like image 110
Jesse van Assen Avatar answered Nov 08 '25 09:11

Jesse van Assen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!