我遇到了EF Update方法的问题。
我有一个包含多个信息和其他复杂对象的对象 例如,当我调试 object.otherObject 包含数据时。
然后我用以下行更新它:
_dbContext.Update(object);
问题是在 更新 调用之后,我的 object.otherObject 会丢失其值并变为null。
尝试使用其他操作(用户界面操作)和相同的对象(不同的值)时,我不会遇到这个问题。
根据我对EF更新的理解,它应该将对象标记为已修改但保持不变。
编辑:
我的映射文件是:
internal class ObjectConfiguration: EntityTypeConfiguration<Object>
{
public ObjectConfiguration()
{
ToTable("TABLE_NAME", Properties.Settings.Default.DBSchema);
HasKey(s => s.Id);
Property(s => s.Id).HasColumnName("COLUMNNAME");
}
}
编辑2:
_dbContext是一个按照EF 5存储库和工作单元格构建的自定义对象:
像这样:
public class UserManager : IDisposable
{
private readonly IRepository _dbContext;
}
public interface IRepository
{
TEntity Update<TEntity>(TEntity entity) where TEntity : class;
}
编辑3:
在执行Attach函数时,对象实际上会清空其值:
public TEntity Update<TEntity>(TEntity entity) where TEntity : class
{
try
{
TEntity attachedEntity = Set<TEntity>().Attach(entity);
var entry = Entry(entity);
entry.State = System.Data.EntityState.Modified;
}
catch(Exception e)
{
}
return entity;
}
答案 0 :(得分:2)
我不知道你的映射是怎样的,但你可以使用这样的东西
public class Example
{
//ohter properties
[Column("id_reference")
public int IdReference { get; set; }
[ForeignKey("IdReference ")]
public virtual Reference ReferenceObj { get; set; }
}
在此示例中,仅映射IdReference属性并将ReferenceObj属性设置为IdReference,使用您必须在加载此属性时指定的虚拟修饰符,为此,请在查询中使用.Include(“ReferenceObj”) (示例dbContext.Examples.Where(x =&gt; x.Id&gt; 0).Include(“ReferenceObj”)。 这可以适用于您的情况,因为只映射了IdReference属性