【问题标题】:Update object when using entity splitting - code first使用实体拆分时更新对象 - 代码优先
【发布时间】:2015-06-01 11:52:35
【问题描述】:

我有一个名为 Document 的类,我将其拆分为两个实体,以便分隔一个昂贵的二进制字段:

[Table("Document")]
public class Document
{
    [Key]
    public int Id { get; set; }

    ... other fields ...

    [Required]
    public virtual DocumentBinary DocumentBinary { get; set; }
}

[Table("Document")]
public class DocumentBinary
{
    [Key, ForeignKey("Document")]
    public int DocumentId { get; set; }

    public Document Document { get; set; }

    public byte[] DocumentData { get; set; }
}

所以,一切正常,两个实体共享同一个数据库表,并且 DocumentData 仅在需要时加载。

但是,在更新 Document 实体时,我收到一条错误消息,指出 'DocumentBinary is required'。

当我从 DocumentBinary 虚拟属性中删除 [Required] 属性时,我收到以下错误:

实体类型“Document”和“DocumentBinary”不能共享表“Documents”,因为它们不在同一类型层次结构中,或者它们之间没有有效的一对一外键关系和匹配的主键。

我显然可以这样做:

var test = document.DocumentBinary;

更新文档对象之前:

documentRepository.Update(document);

这将根据我的请求加载二进制数据并保存更改而不会出现任何问题,但重点是我不需要这样做。

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

    这可以使用 fluent API 来实现。如果您删除数据注释并在您的 OnModelCreating 中添加它,它应该可以工作。

     protected override void OnModelCreating(DbModelBuilder modelBuilder)
     {
         modelBuilder.Entity<Document>().HasRequired(d => d.DocumentBinary).
                                         WithRequiredDependent(db => db.Document);
    
     }
    

    【讨论】:

    • 谢谢。它可能会起作用(以前尝试过,但顺序错误!),但我更喜欢使用数据注释,因为我发现它们更具描述性。我自己设法找到了一个解决方案,我稍后会发布。
    【解决方案2】:

    我设法通过覆盖 DocumentRepository 中的 Update 方法来解决它:

    public override void Update(Document document)
    {
        try
        {
            DataContext.Entry(document.DocumentBinary).State = EntityState.Modified; // added this line
            DataContext.Entry(document).State = EntityState.Modified;
        }
        catch (System.Exception exception)
        {
            throw new EntityException("Failed to update document");
        }
    }
    

    我知道它可能与我通过将 DocumentBinary 分配给“test”变量来评估它做同样的事情,但它看起来像是一个更清洁的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多