C# 实体框架核心集null实体的一个属性

C# 实体框架核心集null实体的一个属性,c#,entity-framework,.net-core,.net-core-3.0,ef-core-3.0,C#,Entity Framework,.net Core,.net Core 3.0,Ef Core 3.0,我需要保存一个实现baseEntity的实体 如果我修改了IdStatus,efcore会正确地更新它,但如果IdStatus值在其他道具上没有更改,则updating=>出于某种原因,efcore会将其设置为null idStatus=20=>尝试更新到12=>成功 idStatus=12=>尝试更新描述=>idStatus=null,描述确定 public void Update(TTableEntity updated, int userid) { toSave =

我需要保存一个实现baseEntity的实体

如果我修改了IdStatus,efcore会正确地更新它,但如果IdStatus值在其他道具上没有更改,则updating=>出于某种原因,efcore会将其设置为null

idStatus=20=>尝试更新到12=>成功

idStatus=12=>尝试更新描述=>idStatus=null,描述确定

public void Update(TTableEntity updated, int userid)
    {
        toSave = GetById(updated.Idnrr);

        PropertyCopier<TTableEntity, TTableEntity>.Copy(updated, toSave);
                    //tosave.idstatus == 20 ! 
        toSave.DateMod = DateTime.Now;
        toSave.UserMod = (short)userid;

        _dbContext.Update(toSave);
        _dbcontext.SaveChanges();//after save => idstatus == null
    }
编辑:“再次”

我尝试将状态值从20更改为12=>updated.status=12,在propscopy之后更改为Save.status=12(在复制为20之前)=>SaveChanges()db.status=12正常,它可以工作(C)

但是

如果我需要更新一些其他值,或者再次执行save,则在(C)之后(使用updated.status=12和db.status=12)=>在proposcopy toSave.status=12之后(事件之前)=>saveChanges()db/toSave status prop变为null(D)

图:idStatus Prop的propCopier方法调试=>即使使用其他道具,即使使用相同/或不相同的idStatus值,它也能工作(A,B)

public static class PropertyCopier<TSource, TTarget> where TSource : class where TTarget : class
{
    public static void Copy(TSource source, TTarget target)
    {
        var sourceProperties = source.GetType().GetProperties();
        var targetProperties = target.GetType().GetProperties();

        foreach (var sourceProperty in sourceProperties)
        {
            var targetProperty = targetProperties.SingleOrDefault(x =>
                sourceProperty.Name.ToLower() == x.Name.ToLower() && sourceProperty.PropertyType == x.PropertyType);
            if (targetProperty == null)
                continue;
            var value = sourceProperty.GetValue(source);
            targetProperty.SetValue(target, value);
        }
    }
}
测试A是否有效(副本已注释)

即使我手动设置idstatus,测试B f****k(复制未注释) (tosave.idstatus=updated.idstatus) 避免使用

PropertyCopier<TTableEntity, TTableEntity>.Copy(updated, toSave);
PropertyCopier.Copy(更新,保存);

并手动将
更新的
实体的属性逐个分配到
以保存

您可以为副本添加代码。。。这将有助于解决问题,因为问题最有可能发生在您认为您是如何更改/复制属性的实现上,而不是EF的问题-我不这么认为,因为如果我将idStatus更改为12,更新方法将工作,并且-在propCopy之后,idStatus设置正确有趣。。。您能提供表示[toSave]的实体的完整代码吗。包括完整的PropertyCopier类..@Seabizkit在这里为您提供。我想说,这是因为您的代码有问题,我可以访问一个副本,可能是一个真正精简的版本,有问题,在GIthub中宿主或其他东西,而不必查看所有代码,或者您正在做的足够好,这很难猜测。它不会改变,我尝试手动设置为save.IdStatus,并使用保存在db中的相同值(这意味着我不想更改值db.IdStatus=20/toSave.IdStatus=20)在保存更改后,如果我再次尝试更新(null为20)=>成功,则我有db.IdStatus=null,db.idstatus=20我添加了更多示例这不是我问题的答案,但没关系
PropertyCopier<TTableEntity, TTableEntity>.Copy(updated, toSave);