繁体   English   中英

实体框架在表拆分中保存一对一关系

[英]Entity Framework Saving One to One relation in Table Splitting

为了性能,我决定按照这种技术拆分表。 所以基本上我有第二个实体来保存二进制字段。 这些是我的课程:

public partial class CustomerDoc
{
    public byte[] Document { get; set; }
    public int CustomerID { get; set; }

    public virtual Customer customer { get; set; }
}

public partial class Customer
{
    public int CustomerID { get; set; }
    public string Name { get; set; }

    public virtual CustomerDoc CustomerDoc { get; set; }
}

现在,当我尝试使用上载的文件更新现有Customer实例中的Document属性时,此值不会保存在数据库中,而是保存其他属性,但不保存Document。

    [HttpPost]
    public virtual ActionResult Edit(Customer customer, HttpPostedFileBase file)
    {
        if (ModelState.IsValid)
        {
            //code to modify other properties 

            if (file != null && file.ContentLength > 0)
            {
                BinaryReader b = new BinaryReader(file.InputStream);
                byte[] binData = b.ReadBytes((int)file.InputStream.Length);

                customer.CustomerDoc= new CustomerDoc { CustomerID = customer.CustomerID, Document = binData };

            }

            db.Entry(customer).State = EntityState.Modified;
            db.SaveChanges();
         }

我已检查其他属性是否已正确修改。

CustomerCoc在调用SaveChanges后有一个值,但不保存在数据库中。

此外,我试图在IF语句中的同一客户的第二个实例中更新,但是我得到了一堆错误

这是映射详细信息:

Mapping Details - CustomerDoc
  Maps to Customer
    Column Mapping
       CustomerID : int <-> *CustomerID : Int32
       Document : varbinary(max) <-> Document: Binary 

使用以下代码替换代码中的内部if块:

if (file != null && file.ContentLength > 0)
{
    BinaryReader b = new BinaryReader(file.InputStream);
    byte[] binData = b.ReadBytes((int)file.InputStream.Length);

    var customerDoc = new CustomerDoc { CustomerID = customer.CustomerID, Document = binData };
    db.Set<CustomerDoc>().Add(customerDoc);
}

解决方案是独立于客户保存customerDoc实体。

if (file != null && file.ContentLength > 0)
{
    BinaryReader b = new BinaryReader(file.InputStream);
    byte[] binData = b.ReadBytes((int)file.InputStream.Length);

    var customerDoc = new CustomerDoc { CustomerID = customer.CustomerID, Document = binData };
    db.Entry(customerDoc).State = EntityState.Modified;
    db.SaveChanges();
}

暂无
暂无

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

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