多対多のコンテキストを実現しようとしています。製品はさまざまな素材で作ることができ、素材ごとに価格が異なります。
ここに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">
コントローラーにブレークポイントを設定すると、Product オブジェクトが 0 ProductMaterials オブジェクトで作成されていることがわかります。
これが正しい方法であるかどうかはわかりませんが、ダウンロードしたサンプルコードを見ると、更新がはるかに複雑になることがわかります。