实体框架模型属性无法正确更新 [英] Entity Framework Model Property not update properly

查看:374
本文介绍了实体框架模型属性无法正确更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下2种模型。

GeoLocation 模型:

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 / p>

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();
}

像上面一样,我需要更新Provider Table的Location对象。是给出奇怪的结果。这是当传入位置对象有Id,我们说15.然后我需要更新到提供程序表位置Id .But之后的代码它更新因为16不是15.你能告诉我为什么吗?这里的根本问题是什么?

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 ?

注意:我使用默认EF约定映射。

UPDATE:我发现这里的问题。当我把 provider.Location = location; GeoLocation 自动增加ID增加1 。这是什么原因。我怎么能避免这种情况?

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 ?

推荐答案

您是如何获得位置的?问题是你的EF上下文( Catalog )认为该位置是一个要持久化的新对象(=它生成插入到位置表中)。

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.

这可能是一个诀窍:

if (location.Id > 0) {
    Catalog.GeoLocations.Attach(location);
} 

provider.Location = location;

这篇关于实体框架模型属性无法正确更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆