在同一DataContext中添加与不同父实体中的子项相同类型的集合

时间:2014-09-17 13:04:14

标签: c# entity-framework dbcontext

类别集合将是交易实体或产品实体的子项。 和产品集合始终是类别的孩子。但是,在向产品添加类别集合时,它还会显示在事务中添加的类别。 这是代码。

    private void buttonUpdate_Click(object sender, RoutedEventArgs e)
    {
        using (var data = new ProductContext())
        {
            var t = new Transaction();
            data.Transaction.Add(t);
            t.Dscr = "t1";

            var c = new Category{  Name= "cat under trans 1"};
            t.Categories.Add(c);
            var p = new Product{ Name="p 1"};

            var c1 = new Category{  Name= "cat under product 1"};
            p.Categories.Add(c1);

            //******p.Categories ALSO SHOWS t.Categories **************//

            c.Products.Add(p);

            data.SaveChanges(); 
        }
    }

public class ProductContext : DbContext
{
    public ProductContext()
    {
        this.Database.Connection.ConnectionString = "workstation id=.;packet size=4096;user id=sa ;Password =123;data source=.; Initial Catalog=YRX;persist security info=False; MultipleActiveResultSets=True; connection timeout=5"; //ConnectionString                            // ConnectionString;
        //this.Configuration.AutoDetectChangesEnabled = true;

    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
        //base.OnModelCreating(modelBuilder);
    }
    public DbSet<Transaction> Transaction { get; set; }
}

public class Transaction
{
    public Transaction()
    {
        this.Categories = new ObservableCollection<Category>();
    }
    [Key]
    public int TransId { get; set; }
    public string Dscr { get; set; }
     [ForeignKey("TransId")] 
    public virtual ObservableCollection<Category> Categories { get; private set; }

}

public class Category
{
    public Category()
    {
        this.Products = new ObservableCollection<Product>();
    }
    [Key]
    public int CategoryId { get; set; }
    public string Name { get; set; }
    [ForeignKey("CategoryId")] 
    public virtual ObservableCollection<Product> Products { get; private set; }
    public int? ProductId { get; set; }
    public int? TransId { get; set; }
}
public class Product
{
    public Product()
    {
        this.Categories = new ObservableCollection<Category>();
    }
    [Key]
    public int ProductId { get; set; }
    public string Name { get; set; }
    //public virtual Category Category { get; set; }
    public int CategoryId { get; set; }
    [ForeignKey("ProductId")] 
    public virtual ObservableCollection<Category> Categories { get; private set; }
}

0 个答案:

没有答案