收藏属性未在保存时正确添加到父级

时间:2013-08-27 13:00:17

标签: c# asp.net-mvc

请看下面的代码示例。

它的作用:

  1. 迭代一大堆客户。如果它已经知道客户,它将检索该客户的现有数据库对象(这是问题所在的部分)。否则,它会创建一个新对象(这很好)。
  2. 社会安全号码匹配(CPR)的所有贷款将被添加到新客户或现有客户。
  3. 问题:它适用于新客户对象,但是当我检索现有客户对象时,贷款在保存时失去与客户的关系(CustomerID = null)。它们仍然保存在数据库中。

    有什么想法吗?

    protected void BuildCustomerData()
    {
        Console.WriteLine("  Starting the customer build.");
    
        var counter = 0;
        var recycleCount = 100;
        var reportingCount = 100;
    
        var sTime = DateTime.Now;
    
        var q = from c in db.IntermediaryRkos
                select c.CPR;
    
        var distincts = q.Distinct().ToArray();
        var numbersToProcess = distincts.Count();
    
        Console.WriteLine("  Identified " + numbersToProcess + " customers. " + (DateTime.Now - sTime).TotalSeconds);
    
        foreach (var item in distincts)
        {
            var loans = from c in db.IntermediaryRkos
                        where c.CPR == item
                        select c;
    
            var existing = db.Customers.Where(x => x.CPR == item).FirstOrDefault();
    
            if (existing != null)
            {
                this.GenerateLoanListFor(existing, loans);
                db.Entry(existing).State = System.Data.EntityState.Modified;
            }
            else
            {
                var customer = new Customer
                {
                    CPR = item,
                };
    
                this.GenerateLoanListFor(customer, loans);
                db.Customers.Add(customer);
                db.Entry(customer).State = System.Data.EntityState.Added;
            }
    
            counter++;
    
            if (counter % recycleCount == 0)
            {
                this.SaveAndRecycleContext();
            }
    
            if (counter % reportingCount == 0)
            {
                Console.WriteLine("    Processed " + counter + " customers of " + numbersToProcess + ".");
            }
        }
    
        db.SaveChanges();
    }
    
    protected void GenerateLoanListFor(Customer customer, IQueryable<IntermediaryRko> loans)
    {
        customer.Loans = new List<Loan>();
    
        foreach (var item in loans.Where(x => x.DebtPrefix == "SomeCategory").ToList())
        {
            var transformed = StudentLoanMap.CreateFrom(item);
    
            customer.Loans.Add(transformed);
    
            db.Entry(transformed).State = System.Data.EntityState.Added;
        }
    }
    

    编辑1:

    正如所指出的,我手动设置状态。这是由于RecycleContext调用,它是为实现最大数据库事务性能而实现的:

    protected void SaveAndRecycleContext()
    {
        db.SaveChanges();
        db.Dispose();
        db = new SolutionDatabase();
        db.Configuration.AutoDetectChangesEnabled = false;
        db.Configuration.ValidateOnSaveEnabled = false;
    }
    

1 个答案:

答案 0 :(得分:0)

现有贷款与否,当您致电

时,您将消灭客户。贷款房产

customer.Loans = new List<Loan>();