Cannot get relationship to update for navigation properties in entity framework

后端 未结 3 653
梦谈多话
梦谈多话 2020-12-05 21:38

I am currently using EF4.3 and Code First. Creation of my objects works (via my views - just using the auto-generated Create), but when I attempt to edit an object, it does

3条回答
  •  长情又很酷
    2020-12-05 22:30

    There are several options here, I will list 3 of them:

    Option 1: Using GraphDiff

    *This needs the Configuration.AutoDetectChangesEnabled of your context set to true.

    Just install GraphDiff with NuGet

    Install-Package RefactorThis.GraphDiff
    

    Then

    using (var context = new Context())
    {
        var customer = new Customer()
        {
            Id = 12503,
            Name = "Jhon Doe",
            City = new City() { Id = 8, Name = "abc" }
        };
    
        context.UpdateGraph(customer, map => map.AssociatedEntity(p => p.City));
        context.Configuration.AutoDetectChangesEnabled = true;
    
        context.SaveChanges();
    }
    

    For more details about GraphDiff look here.

    Option 2: Find and Edit

    Searching your entity with EF to track it to the context. Then edit the properties.

    *This needs the Configuration.AutoDetectChangesEnabled of your context set to true.

    var customer = new Customer()
    {
        Id = 12503,
        Name = "Jhon Doe",
        City = new City() { Id = 8, Name = "abc" }
    };
    
    using (var context = new Contexto())
    {
        var customerFromDatabase = context.Customers
                                          .Include(x => x.City)
                                          .FirstOrDefault(x => x.Id == customer.Id);
    
        var cityFromDataBase = context.Cities.FirstOrDefault(x => x.Id == customer.City.Id);
    
        customerFromDatabase.Name = customer.Name;
        customerFromDatabase.City = cityFromDataBase;                
    
        context.Configuration.AutoDetectChangesEnabled = true;
        context.SaveChanges();
    }
    

    Option 3: Using a scalar property

    In a matter of performance this is the best way, but it mess your class with database concerns. Because you will need to create a scalar (primitive type) property to map the Id.

    *In this way there is no need to set the Configuration.AutoDetectChangesEnabled to true. And also you won't need to do a query to the database to retrieve the entities (as the first two options would - yes GraphDiff does it behind the scenes!).

    var customer = new Customer()
    {
        Id = 12503,
        Name = "Jhon Doe",
        City_Id = 8,
        City = null
    };
    
    using (var contexto = new Contexto())
    {
        contexto.Entry(customer).State = EntityState.Modified;
        contexto.SaveChanges();
    }
    

提交回复
热议问题