实现EF6代码的一般方法

时间:2015-02-16 12:46:33

标签: c#-4.0 generics entity-framework-6 .net-reflector

我正在使用EF6 Code First(通用存储库概念)

示例代码创建记录:

Generic.cs:

public T Create<T>(T t) where T : class
    {
        T newEntry = this.dbContext.Set<T>().Add(t);
        this.SaveChanges();
        return newEntry;
    }

实际代码:

 var customer = new Customer{
                      Name = "Adams",
                      Amount = 1000
                    };

CustomerId是AutoIdentity列它会自动生成Id。

与产品具有一对多关系的客户表(产品表中的CustomerID FK)

现在我在产品列表中添加新的CustomerID

var productsList = new List<Product>
{
    new Product
       {
           ProdName = "crocin", 
           Date = DateTime.Parse("2003-09-01"),
           Customer.CustomerId = newCustomerId // 
       },
    new Product
       {
           ProdName = "crocin1", 
           Date = DateTime.Parse("2003-09-01"),
           Customer.CustomerId = newCustomerId  // 
       },
    new Product
       {
           ProdName = "crocin2", 
           Date = DateTime.Parse("2003-09-01"),
           Customer.CustomerId = newCustomerId  // 
       } 
};

现在我打了两次数据库,因为首先我得到了CustomerId,然后我将新的CustomerId分配给所有选定的产品。

以下是代码:

var newCustomer = Generic.Create<Customer>(customer);

迭代产品列表,我正在将newCustomerId分配到产品中..

foreach(var product in productList)
{
  product.CustomerId = newCustomerId;

  Generic.Create<Product>(product); 
} 

是否可以将此代码更改为更通用的方式来实现这样的事情..

Create(T parentTable, List<T> childTableList)
{
    // First Inserting ParentTable

     db.SaveChanges();

    //Fetching ID

    // Inserting Into ChildTables..

    db.SaveChanges();
}

请建议我延长此代码......

1 个答案:

答案 0 :(得分:0)

问题在于您错过了Customer -> Products关联。尝试在Products课程中添加对Customer的引用:

public class Customer
{
    public Customer()
    {
        this.Products = new List<Product>();
    }

    // your key
    public int CustomerId { get; set; }

    public string Name { get; set; }
    public int Amount { get; set; }

    // ... rest of your data

    // the new association
    public virtual ICollection<Product> Products { get; set; }
}

现在您可以在一次通话中添加它们:

var productsList = new List<Product>
{
    new Product
       {
           ProdName = "crocin", 
           Date = DateTime.Parse("2003-09-01"),
           Customer.CustomerId = newCustomerId // 
       },
    new Product
       {
           ProdName = "crocin1", 
           Date = DateTime.Parse("2003-09-01"),
           Customer.CustomerId = newCustomerId  // 
       },
    new Product
       {
           ProdName = "crocin2", 
           Date = DateTime.Parse("2003-09-01"),
           Customer.CustomerId = newCustomerId  // 
       } 
};

var newCustomer = new Customer();

foreach (var product in productsList)
    newCustomer.Products.Add(product);

然后将它们添加到上下文中:

var newCustomer = Generic.Create<Customer>(newCustomer);
相关问题