【问题标题】:Entity Framework Saving One to One relation in Table Splitting实体框架在表拆分中保存一对一关系
【发布时间】:2013-08-04 09:26:36
【问题描述】:

为了性能,我决定在this technique之后拆分一个表。 所以基本上我有第二个实体来保存一个二进制字段。 这些是我的课程:

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; }
}

现在,当我尝试使用上传的文件更新现有客户实例中的 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();
         }

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

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

我还尝试在 IF 语句中更新同一客户的第二个实例,但出现一堆错误

这是映射细节:

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

【问题讨论】:

  • 您是否进行了适当的关联?你能发布你的模型配置吗?
  • CustomerDoc 主键中有 CustomerID 吗?
  • 是的,它被标记为实体键

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


【解决方案1】:

将代码中的内部 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);
}

【讨论】:

【解决方案2】:

解决方案是独立于客户保存 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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    相关资源
    最近更新 更多