我正在尝试实现多对多的上下文。产品可以由不同的材料制成,并且这些材料的价格不同:
这是product.cs:
namespace test.Models
{
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System;
using System.Collections.Generic;
public partial class Product
{
public Product()
{
this.ProductMaterials = new HashSet<ProductMaterial>();
}
public int Id { get; set; }
[DisplayName("Product name"),
Required(ErrorMessage = "Product Name is required"),
StringLength(100)]
public string Name { get; set; }
[Required]
public virtual ICollection<ProductMaterial> ProductMaterials { get; set; }
}
}
这是 ProductMaterials.cs:
namespace test.Models
{
using System;
using System.Collections.Generic;
public partial class ProductMaterial
{
public int Id { get; set; }
public int ProductId { get; set; }
public int MaterialId { get; set; }
public string PriceOffset { get; set; }
public virtual Material Material { get; set; }
public virtual Product Product { get; set; }
}
}
和 Material.cs:
namespace test.Models
{
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System;
using System.Collections.Generic;
public partial class Material
{
public Material()
{
this.ProductMaterials = new HashSet<ProductMaterial>();
}
public int Id { get; set; }
[Required,DisplayName("Material"),
StringLength(100)]
public string Mat { get; set; }
[DefaultValue(0), Required]
public decimal PriceOffset { get; set; }
public virtual ICollection<ProductMaterial> ProductMaterials { get; set; }
}
}
现在尝试在上下文中添加正确的信息,以便可以从表单创建对象,并尝试使其尽可能简单,以便通过小步骤来理解这一点。
testContext.cs 具有以下内容:
使用 System.Data.Entity;
namespace test.Models
{
public class testContext : DbContext
{
System.Data.Entity.DropCreateDatabaseIfModelChanges<test.Models.testContext>());
public testContext() : base("name=testContext")
{
}
public DbSet<Product> Products { get; set; }
public DbSet<Manufacturer> Manufacturers { get; set; }
public DbSet<ProductMaterial> ProductMaterials { get; set; }
public DbSet<Material> Materials { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>()
.HasMany(c => c.ProductMaterials);
}
}
}
这是我发布的额外数据:
<input type="text" value="1" name="ProductId">
<input type="text" value="1" name="MaterialId">
<input type="text" value="0" name="PriceOffset">
当我在控制器中设置断点时,我看到使用 0 个 ProductMaterials 对象创建了一个 Product 对象。
不确定这是否是正确的方法,我在下载的示例代码中看到更新会复杂得多。