无法更新实体框架6中的外键

本文关键字:框架 更新 实体 | 更新日期: 2023-09-27 18:19:04

我正试图对外键进行简单的更新,但脚本从未发送过。

下面是我使用的代码:
using (var db = new MyContext())
{
      db.Entry<Contact>(newContact).State = EntityState.Modified;
      newContact.ContactOwner = db.Person.Find(3);
      db.SaveChanges();
}

EF6更新Persons表中列的其余部分,但不更新Persons表中的Contact_Id。

人的实体:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Contact> ContactList { get; set; }
}

联系实体:

public class Contact
{
    public int Id { get; set; }
    public string Email { get; set; }
    public string TelNo { get; set; }
    public Person ContactOwner { get; set; }
}

我在这里错过了什么?

请帮忙!

无法更新实体框架6中的外键

由于您正在使用独立关联。

  • ContactList中添加和删除关系,但需要从两个Person中检索。

    db.Entry(newContact).State = EntityState.Modified;
    var p1 = db.Set<Person>().Include(p => p.ContactList)
        .FirstOrDefault(p =>p.Id == 1);
    p1.ContactList.Remove(newContact);
    var p3 = db.Set<Person>().Include(p => p.ContactList)
        .FirstOrDefault(p => p.Id == 3);
    p3.ContactList.Add(newContact);
    db.SaveChanges();
    
  • 或者您可以使用断开连接的对象,但您需要手动管理关系。

    db.Entry(newContact).State = EntityState.Modified;
    var p1 = new Person { Id = 1 };
    db.Entry(p1).State = EntityState.Unchanged;
    var p3 = new Person { Id = 3 };
    db.Entry(p3).State = EntityState.Unchanged;
    var manager = ((IObjectContextAdapter)db).ObjectContext.ObjectStateManager;
    manager.ChangeRelationshipState(newContact, p1, item => item.ContactOwner,
         EntityState.Deleted);
    manager.ChangeRelationshipState(newContact, p3, item => item.ContactOwner,
         EntityState.Added);
    db.SaveChanges();
    

p

您可能需要重新考虑添加外键值,为了使一切更容易,只需提及Id就可以更新外键。

这是我直到早上很晚才完成的东西,可以/应该再重构一些…

   protected static async Task<int> SaveEntity<t>(t obj) where t : BaseModel
    {
        try
        {
            using (DatabaseContext db = GetDbContext())
            {
                //get the basemodel/fk reference properties
                IEnumerable<PropertyInfo> props = obj.GetType().GetProperties().Where(p => p.PropertyType.BaseType == typeof(BaseModel));
                if (obj.Id <= 0)
                {//insert
                    db.Entry(obj).State = EntityState.Added;
                    //set fk reference props to unchanged state
                    foreach (PropertyInfo prop in props)
                    {
                        Object val = prop.GetValue(obj);
                        if (val != null)
                        {
                            db.Entry(val).State = EntityState.Unchanged;
                        }
                    }
                    //do insert
                    return await db.SaveChangesAsync();
                }
                else
                {//update
                    //get the posted fk values, and set them to null on the obj (to avaid dbContext conflicts)
                    Dictionary<string, int?> updateFKValues = new Dictionary<string, int?>();
                    foreach (PropertyInfo prop in props)
                    {
                        BaseModel val = (BaseModel)prop.GetValue(obj);
                        if (val == null)
                        {
                            updateFKValues.Add(prop.Name, null);
                        }
                        else
                        {
                            updateFKValues.Add(prop.Name, val.Id);
                        }
                        prop.SetValue(obj, null);
                    }
                    //dbContext creation may need to move to here as per below working example
                    t dbObj = (t)db.Set(typeof(t)).Find(new object[] { obj.Id }); //this also differs from example
                    //update the simple values
                    db.Entry(dbObj).CurrentValues.SetValues(obj);
                    //update complex values
                    foreach (PropertyInfo prop in props)
                    {
                        Object propValue = null;
                        if (updateFKValues[prop.Name].HasValue)
                        {
                            propValue = (BaseModel)db.Set(prop.PropertyType).Find(new object[] { updateFKValues[prop.Name] });
                        }
                        prop.SetValue(dbObj, propValue);
                        if (propValue != null)
                        {
                            db.Entry(propValue).State = EntityState.Unchanged;
                        }
                    }
                    //do update
                    return await db.SaveChangesAsync();
                }
            }
        }
        catch (Exception ex)
        {
            ExceptionHelper.Log(ex);
            throw;
        }
    }

基本上这是因为EntryState.Modified只是寻找标量属性(原始类型)和独立的关联(你的情况下),你没有它。

有几种方法可以做到这一点,@Yuliam指出了其中的一些方法

当需要更新主对象和附加的外键对象时,此解决方案对我有效。

    public virtual async Task<Result<TEntity>> Update<TEntity>(TEntity entity) where TEntity : class
    {
        Result<TEntity> returnResult = new Result<TEntity>();
        try
        {
            //get the fk reference properties
            IEnumerable<PropertyInfo> props = entity.GetType().GetProperties().Where(p => p.PropertyType.BaseType == typeof(object));
            //set fk reference props to modified state
            foreach (PropertyInfo prop in props)
            {
                Object val = prop.GetValue(entity);
                if (val != null)
                {
                    dbContext.Entry(val).State = EntityState.Modified;
                }
            }

            dbContext.Entry(entity).State = EntityState.Modified;
            await dbContext.SaveChangesAsync();
            returnResult.SetSuccess(result: entity);
        }
        catch (Exception e)
        {
            log.Error(e);
            returnResult.SetError(exception: e);
        }
        
        return returnResult;
    }