简体   繁体   English

实体框架:设置回默认值

[英]Entity Framework: Set back to default value

I'm trying to update an entity using a stub. 我正在尝试使用存根更新实体。 This works fine for changing records, unless I try to set the value back to the default value forr the column. 除非我尝试将列的值重新设置为默认值,否则更改记录效果很好。 Eg: If the default value is 0, I can change to and from any value except zero, but the changes aren't saved if I try to set it back to zero. 例如:如果默认值为0,则可以在除零以外的任何值之间进行切换,但是如果尝试将其设置回零,则不会保存更改。 This is the code I'm using: 这是我正在使用的代码:

var package = new Package() {
    PackageID = 4
};
...
public static void EditPackage(Package package) {
    using(var context = new ShopEntities()) {
        context.Packages.MergeOption = MergeOption.NoTracking;
        var existing = new Package() {
            PackageID = package.PackageID
        };
        context.AttachTo("Packages", existing);
        context.ApplyPropertyChanges("ShopEntities.Packages", package);
        context.AcceptAllChanges(); // doesn't make a difference
        System.Diagnostics.Debug.WriteLine((package.DateSent.HasValue ? package.DateSent.Value.ToString("D") : "none") + "\t\t" + package.IsReceived);
        context.SaveChanges();
    }
}

In the example above, DateSent's default value is null (It's a DateTime?), and I can also set it to any value other than null, and the debug line confirms the correct properties are set, they're just not saved. 在上面的示例中,DateSent的默认值为null(这是DateTime?),我还可以将其设置为null以外的任何其他值,并且调试行会确认设置了正确的属性,只是没有保存它们。 I think I must be missing something. 我想我一定很想念东西。

Thanks for any help. 谢谢你的帮助。

Turns out what I needed to do was manually mark each property in the new item as modified. 原来我需要做的是手动将新项目中的每个属性标记为已修改。

/// <summary>
/// Sets all properties on an object to modified.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="entity">The entity.</param>
private static void SetAllPropertiesModified(ObjectContext context, object entity) {
    var stateEntry = context.ObjectStateManager.GetObjectStateEntry(entity);
    // Retrieve all the property names of the entity
    var propertyNames = stateEntry.CurrentValues.DataRecordInfo.FieldMetadata.Select(fm => fm.FieldType.Name);
    foreach(var propertyName in propertyNames) {// Set each property as modified
        stateEntry.SetModifiedProperty(propertyName);
    }
}

You are creating a new package (with the id of an existing package), which you are calling "existing". 您正在创建一个新的程序包(具有现有程序包的ID),您称其为“现有”。 You are then attaching it as if it was an existing package. 然后,您将其附加为已存在的软件包。 You should load this package from the database and then attach it. 您应该从数据库加载此程序包,然后附加它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM