c# - Entity Framework 6 更新多对多而不更新或加载 Child

标签 c# entity-framework many-to-many

我想更新与其他记录有多对多关系的记录。 我的问题是,它总是尝试更新它的 child ,但失败了,因为 child 有必填字段,而我只提供 ID。

我不想加载子对象。我只希望它插入地址并更新多对多表。

Address 有一个 IEnumerable,其中包含 ProductID,其他字段为空或具有默认值(整数和 bool 值)。

我收到以下错误:

Property: Name Error: Please enter a Name Property: Description Error: Please enter a Description Property: Category Error: Please enter a Category

[HttpPost]
    public ActionResult ReceiveOrder(Address address)
    {
        EFDbContext context = new EFDbContext();

            context.Addresses.Add(address);
            context.SaveChanges();
            context.Dispose();
            return Json(new { success = true, responseText = "Okay" }, JsonRequestBehavior.AllowGet);
    }

地址类:

    public class Address
{
    public int AddressID { get; set; }
    public string Name { get; set; }
    public string Street { get; set; }
    public virtual List<Product> Products { get; set; }
    public bool Giftwrap { get; set; }
}

产品类别

public class Product
{

    [HiddenInput(DisplayValue =false)]
    public int ProductID { get; set; }
    [Required(ErrorMessage ="Please enter a Name")]
    public string Name { get; set; }
    [DataType(DataType.MultilineText)]
    [Required(ErrorMessage = "Please enter a Description")]
    public string Description { get; set; }
    [Required(ErrorMessage = "Please enter a Price")]
    public decimal Price { get; set; }
    [Required(ErrorMessage = "Please enter a Category")]
    public string Category { get; set; }

    public byte[] ImageData { get; set; }
    public string ImageMimeType { get; set; }

    public virtual List<Address> Addresses { get; set; }
}

我如何告诉 EF 它只应该插入地址并更新关系表。我不想通过先加载产品来产生开销。我也不喜欢在不必要时访问 Products 表。

最佳答案

你应该使用:

  • Attach方法 (DbSet) 激活修改跟踪。

Attach is used to repopulate a context with an entity that is known to already exist in the database

  • Entry方法 (DbContext) 能够设置附加实体的状态。

您可能还想阅读 Add/Attach and Entity States

对于许多产品:

public ActionResult ReceiveOrder(Address address)
{
    EFDbContext context = new EFDbContext();

    context.Set<Addresses>().Attach(address);
    foreach(Product p in address.Products) {
        context.Set<Products>().Attach(p);
    }
    context.Entry(address).State = EntityState.Added; 

    context.SaveChanges();
    context.Dispose();
    return Json(new { success = true, responseText = "Okay" },
            JsonRequestBehavior.AllowGet);
}

关于c# - Entity Framework 6 更新多对多而不更新或加载 Child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33213088/

相关文章:

c# - 如何从 jQuery 自动完成的 C# Controller 操作返回 Json 标签/值对

c# - 我怎样才能找出是什么阻止了对象的垃圾收集?

java - 为什么 @ManyToMany 不能使用非主键列?

Django 1.8 - 中间多对多直通关系 - 使用 'ManytoManyField' 的结果是什么?

java - 在 jpa 中使用多对多关系时的空表

c# - 多个等待场景中的 HTTPContext

c# - 无法在更新面板中找到上传的文件

c# - 静态类中的静态 DataServiceContext

c# - MVC 4 Beta - 在写入本地名称为 'type' 的属性后,您必须写入属性 ='object' '__type'

entity-framework - Entity Framework 代码优先忽略特定模式