问题
I am having below mentioned 2 models.
GeoLocation Model :
public class GeoLocation {
        public GeoLocation() { }
        public int Id { get; set; }
        public double Latitude { get; set; }
        public double Longitude { get; set; }
    }
Provider Model :
public class Provider
    {
        public Provider()
        {
            Id = Guid.NewGuid();
            Created = DateTime.Now;
        }
        public Guid Id { get; set; }
        [Required]
        public string Name { get; set; }
        public virtual GeoLocation Location { get; set; }
    }
Repository method :
public void SetLocation(string providerKey, GeoLocation location)
        {
            var provider = (from p in Catalog.Providers
                            where p.Key == providerKey
                            select p).Single();
            provider.Location = location;
            Catalog.SaveChanges();
}
As like above I need to update Location object of Provider Table.But Above code is giving weird result.That is when incoming location object having Id let's say 15.Then I need to update that Id into provider tables location Id.But After above code It updates as 16 not as 15.Could you tell me Why ? What is the fundamental issue here ?
Note : I am using Default EF convention mapping.
UPDATE: I have found the issue here.That is when I put provider.Location = location; GeoLocation table Auto increment Id increase by 1.That is the cause.So How could I avoid that ?
回答1:
How did you get the location? The problem is that your EF context (Catalog) believes that the location is a new object to be persisted (= it generates insert into the location table). You must inform catalog that it is already existing object.
This could make a trick:
if (location.Id > 0) {
    Catalog.GeoLocations.Attach(location);
} 
provider.Location = location;
    来源:https://stackoverflow.com/questions/16440587/entity-framework-model-property-not-update-properly