分离的实体不会更新属性

时间:2016-10-05 10:00:04

标签: c# asp.net-mvc entity-framework-6

我有一个附加了子实体的简单对象。 当我更新分离的对象时,不保存具有子对象的属性。我在这个表单上阅读了很多帖子,但无法弄清楚它为什么没有更新。

请参阅此处更新实体的内部方法:

public class HtmlContent : ITextContentItem, ICreateStamp, IEditStamp, IImmutable
{
    // ReSharper disable once UnusedMember.Local
    private HtmlContent()
    {

    }

    public HtmlContent(string name, string description, string text, DateTime creationDate,
        DateTime? lastEditDate, ApplicationUser createdBy, ApplicationUser lastEditedBy)
    {
        this.Name = name;
        this.Description = description;
        this.Text = text;
        this.CreationDate = creationDate;
        this.LastEditDate = lastEditDate;
        this.CreatedBy = createdBy;
        this.LastEditedBy = lastEditedBy;
    }

    public HtmlContent(int id, string name, string description, string text, DateTime creationDate,
        DateTime? lastEditDate, ApplicationUser createdBy, ApplicationUser lastEditedBy)
        : this(name, description, text, creationDate, lastEditDate, createdBy, lastEditedBy)
    {
        this.Id = id;
    }

    public int Id { get; private set; }

    public string Name { get; private set; }

    public string Description { get; private set; }

    public string Text { get; private set; }

    public DateTime CreationDate { get; private set; }

    public DateTime? LastEditDate { get; private set; }

    public ApplicationUser CreatedBy { get; private set; }

    public ApplicationUser LastEditedBy { get; private set; }

    internal HtmlContent SetLastEditInfo(DateTime? lastEditDate, ApplicationUser lastEditedBy)
    {
        if ((lastEditDate.HasValue && lastEditedBy == null) || 
            (!lastEditDate.HasValue && lastEditedBy != null))
        {
            throw new InvalidOperationException($"{nameof(lastEditDate)} and {nameof(lastEditedBy)} must be used together");
        }

        return new HtmlContent(this.Id, this.Name, this.Description, this.Text, this.CreationDate, lastEditDate, this.CreatedBy, lastEditedBy);
    }

    internal HtmlContent UpdateHtmlContent(string name, string description, string text)
    {
        return new HtmlContent(this.Id, name, description, text, this.CreationDate, this.LastEditDate, this.CreatedBy, this.LastEditedBy);
    }
}

请参阅此处的更新方法:

public async Task Edit(int id, string name, string description, string text)
{
    try
    {
        var content = await this.WithId(id);
        this.db.Entry(content).State = EntityState.Detached;

        var currentDate = DateTime.UtcNow;
        var lastEditedBy = this.userProvider.GetCurrentUser();

        content = content.SetLastEditInfo(currentDate, lastEditedBy);
        content = content.UpdateHtmlContent(name, description, text);

        this.db.Entry(content).State = EntityState.Modified;
        await this.db.SaveChangesAsync();
    }
    catch (System.Data.Entity.Validation.DbEntityValidationException ex)
    {
        var errors = ex.EntityValidationErrors;
        throw;
    }
}

所有其他属性都更新得很好。仅更新LastEditedBy。在Create方法中,CreatedBy工作正常,因为它是保存到数据库的新实体。 ApplicationUser属性在代码首先生成的数据库中有外键。

2 个答案:

答案 0 :(得分:4)

我可能错了,因为我从未尝试过这样做,但我可以看到你的模型存在多个问题。

<强> 1。您的数据模型具有私有设置器,并且没有无参数构造函数。
您的数据模型应该只是一组具有公共setter和getter以及无参数构造函数的属性。这允许EF代理导航属性,以便它知道&#39;什么时候设置了一个属性。

<强> 2。填充模型的代码位于模型本身内。
虽然这不是一个大问题,但它不允许您在将来使用类似通用存储库的东西。所有模型都必须知道如何操纵自己,这可能导致一些不可读的代码。查看存储库模式

第3。为导航属性定义外键
同样,虽然这不是100%重要,但它允许您设置相关实体​​,而无需先从数据库中选择它们。您只需设置相关实体​​的ID即可。

<强> 4。您不应创建新实体来设置其属性
打破了EF的跟踪,并且还打破了实体的所有参照完整性。您希望实体在其生命周期中成为同一个对象。这允许修改属性而不会丢失对象和任何使用EF的跟踪。

我的建议是:

public class HtmlContent
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public string Text { get; set; }

    public DateTime CreationDate { get; set; }

    public DateTime? LastEditDate { get; set; }

    public int CreatedById { get; set; }

    public int LastEditedById { get; set; }

    public ApplicationUser CreatedBy { get; set; }

    public ApplicationUser LastEditedBy { get; set; }
}


public HtmlContentService
{
    public async Task Edit(int id, string name, string description, string text)
    {
        try
        {
            var content = await this.WithId(id);

            // no need to detach the object if you arent disposing the context
            //this.db.Entry(content).State = EntityState.Detached; 

            var currentDate = DateTime.UtcNow;
            var lastEditedBy = this.userProvider.GetCurrentUser();

            // these methods could just be moved into this method
            this.SetLastEditInfo(content, currentDate, lastEditedBy);
            this.UpdateHtmlContent(content, name, description, text);

            this.db.Entry(content).State = EntityState.Modified;
            await this.db.SaveChangesAsync();
        }
        catch (System.Data.Entity.Validation.DbEntityValidationException ex)
        {
            var errors = ex.EntityValidationErrors;
            throw;
        }
    }

    private void SetLastEditInfo(
        HtmlContent content, 
        DateTime lastEditDate, 
        ApplicationUser lastEditedBy)
    {
        if ((lastEditDate.HasValue && lastEditedBy == null) || 
            (!lastEditDate.HasValue && lastEditedBy != null))
        {
            throw new InvalidOperationException(
                $"{nameof(lastEditDate)} and {nameof(lastEditedBy)} must be used together");
        }

        content.LastEditDate = lastEditDate;
        content.LastEditedBy = lastEditedBy;
    }

    private void UpdateHtmlContent(
        HtmlContent content, 
        string name, 
        string description, 
        string text)
    {
        content.Name = name;
        content.Description = description;
        content.Text = text;
    }
}

答案 1 :(得分:0)

解决方案是在模型中创建外键属性(数据库中已有外键但首先使用代码生成)。这样,如果有LastEditedBy用户,您可以在构造函数中设置属性。

public class HtmlContent : ITextContentItem, ICreateStamp, IEditStamp, IImmutable
{
    // ReSharper disable once UnusedMember.Local
    private HtmlContent()
    {

    }

    public HtmlContent(string name, string description, string text, DateTime creationDate,
        DateTime? lastEditDate, ApplicationUser createdBy, ApplicationUser lastEditedBy)
    {
        this.Name = name;
        this.Description = description;
        this.Text = text;
        this.CreationDate = creationDate;
        this.LastEditDate = lastEditDate;
        this.CreatedBy = createdBy;

        this.LastEditedBy = lastEditedBy;
        this.LastEditedById = LastEditedBy?.Id; // Set the id if it isn't null
    }

    public HtmlContent(int id, string name, string description, string text, DateTime creationDate,
        DateTime? lastEditDate, ApplicationUser createdBy, ApplicationUser lastEditedBy)
        : this(name, description, text, creationDate, lastEditDate, createdBy, lastEditedBy)
    {
        this.Id = id;
    }

    public int Id { get; private set; }

    public string Name { get; private set; }

    public string Description { get; private set; }

    public string Text { get; private set; }

    public DateTime CreationDate { get; private set; }

    public DateTime? LastEditDate { get; private set; }

    public ApplicationUser CreatedBy { get; private set; }

    [ForeignKey("LastEditedById")] // Set the foreign key to existing property
    public ApplicationUser LastEditedBy { get; private set; }

    // Use a property in the model for saving and not just a property generated by code first in the database
    public string LastEditedById { get; private set; }

    internal HtmlContent SetLastEditInfo(DateTime? lastEditDate, ApplicationUser lastEditedBy)
    {
        if ((lastEditDate.HasValue && lastEditedBy == null) || 
            (!lastEditDate.HasValue && lastEditedBy != null))
        {
            throw new InvalidOperationException($"{nameof(lastEditDate)} and {nameof(lastEditedBy)} must be used together");
        }

        return new HtmlContent(this.Id, this.Name, this.Description, this.Text, this.CreationDate, lastEditDate, this.CreatedBy, lastEditedBy);
    }

    internal HtmlContent UpdateHtmlContent(string name, string description, string text)
    {
        return new HtmlContent(this.Id, name, description, text, this.CreationDate, this.LastEditDate, this.CreatedBy, this.LastEditedBy);
    }
}