如何使Entity Framework仅更新对象依赖项?

时间:2015-03-30 11:59:17

标签: sql-server entity-framework

我想知道如何让Entity Framework更新一个对象,而不是总是为每个新主对象插入一个新对象。

例如:

我有这些对象:

主要对象:

public class ExtraArticleAttributes
{
    [Key]
    public int extraarticleattributes_id { get; set; }
    virtual public WorldData world_data { get; set; }
}

其依赖:

public class WorldData
{
    [Key]
    public int worlddata_id { get; set; }
    public string country { get; set; }

那么,如何在插入新的ExtraArticleAttributes时验证Entity Framework是否已存在WorldData对象且只更新它?

我一直在阅读一些关于它的文章,我注意到实体框架使用HASH代码识别数据库中的现有对象,所以当我从API获取它时,尝试将其插入数据库中,即使对象具有相同的数据,实体框架不像DB中的现有对象那样识别。是否存在make it的方式,不需要向DB请求验证对象是否存在,如果为true则得到它。

1 个答案:

答案 0 :(得分:1)

将实体状态设置为Modified

using System.Data.Entity;

// Assuming that there is already an existing WorldData record in the database with id 1 and country 'foo', and you want to change the country to 'bar'

using (var context = new MyContext())
{
    var extraArticleAttributes = new ExtraArticleAttributes
    {
        world_data = new WorldData
        {
            worlddata_id = 1,
            country = "bar"
        }
    };

    db.ExtraArticleAttributes.Add(extraArticleAttributes);
    db.Entry<WorldData>(extraArticleAttributes.world_data).State = EntityState.Modified;

    db.SaveChanges();

    // world data 1 country is now 'bar'
}