【问题标题】:How to set navigation property in Entity Framework 6 in case of generic entities如果是通用实体,如何在 Entity Framework 6 中设置导航属性
【发布时间】:2018-12-07 07:55:16
【问题描述】:

我已经更新了一个通用的更新方法如下

public virtual void Update<TEntity>(TEntity entity, string modifiedBy = 
null)           where TEntity : class,IEntity
{
  using (var context = new BanyanDbContext())
  {                
    entity.ModifiedDate = DateTime.UtcNow;
    entity.ModifiedBy = modifiedBy;
    var existingEntiy = context.Set<TEntity>().Find(entity.Id);
    context.Entry(existingEntiy).CurrentValues.SetValues(entity);
    context.Entry(existingEntiy).State = EntityState.Modified;                                
    Save(context);
  }
}

此方法适用于更新非引用类型值,但CurrentValues.SetValues() 不会设置或更新导航属性。 在这种情况下如何设置导航属性。

【问题讨论】:

标签: c# entity-framework-6


【解决方案1】:
public TEntity RemoveNavigationProperties(TEntity input)
        {

            foreach (var item in input.GetType().GetProperties().Where(x => x.PropertyType.Namespace == input.GetType().Namespace))
            {
                item.SetValue(input, null);
            }

            return input;
        }

这对我有用。 (我只需要将它们清空)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 2014-08-20
    • 1970-01-01
    相关资源
    最近更新 更多