2015-10-06 45 views
0

我有具有多个实体的模型。例如,我有一个order,它有CustomerId到外键。在模型中,我有一些来自order的字段和customer实体的一些字段。当我保存新记录时,我想首先保存customer,获取新生成的身份值并将其放到order表中。如何实现这一目标?我可以通过从customer表中获得MAX(ID)来实现,但我确信有更好的方法来处理这个问题。如何在MVC模型上获取新生成的标识

这是我的控制器方法:

public ActionResult Create(OrderModels model, FormCollection form) 
{ 
    try 
    { 
     Customer customer = new Customer() { FirstName = model.FirstName, MiddleName = model.MiddleName, SecondName = model.SecondName, Email = model.Email, PhoneNbr = model.PhoneNbr }; 
     int orderSource = Int32.Parse(form["OrderSourceList"]); 
     int paymentType = Int32.Parse(form["PaymentTypeList"]); 
     string warehouseGuid = form["Warehouses"]; 
     ProductLogic productLogic = new ProductLogic(); 
     Product product = productLogic.GetProductByArticle(model.Article); 
     DateTime now = DateTime.Now; 

     SalesOrder salesOrder = new SalesOrder() 
     { 
      OrderNbr = model.OrderNbr, 
      OrderSourceId = orderSource, 
      NpWarehouseRef = new Guid(warehouseGuid), 
      TTN = model.TTN, 
      OrderStatusId = 1, 
      PaymentTypeId = paymentType, 
      OrderDate = DateTime.Now 
     }; 
     using (AccountingRepository repository = new AccountingRepository()) 
     { 

      repository.AddOrUpdate<Customer>(customer); 
      repository.AddOrUpdate<SalesOrder>(salesOrder); 
     } 
     return RedirectToAction("Index"); 
    } 
    catch (Exception e) 
    { 
     return View(); 
    } 
} 

AccountingRepository有dispose方法

public void Dispose() 
{ 
    if (_context != null) 
    { 
     _context.SaveChanges(); 
     _context.Dispose(); 
    } 
} 

Order类:使用系统

; using System.ComponentModel.DataAnnotations; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration;

namespace Accounting.Entity 
{ 
    [Table("SalesOrder", Schema = "dbo")] 
    public class SalesOrder 
    { 
     [Key] 
     [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
     public int? Id { get; set; } 

... 
     public int? CustomerId { get; set; } 

... 
     public virtual Customer Customer { get; set; } 

     internal class Config : EntityTypeConfiguration<SalesOrder> 
     { 
      public Config() 
      { 

       HasRequired(r => r.Customer) 
        .WithMany(r => r.SalesOrder) 
        .HasForeignKey(r => r.CustomerId); 



      } 
     } 
    } 
} 

Customer类:

using System.ComponentModel.DataAnnotations; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations.Schema; 
using System.Data.Entity.ModelConfiguration; 

namespace Accounting.Entity 
{ 
    [Table("Customer", Schema = "dbo")] 
    public class Customer 
    { 
     [Key] 
     [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
     public int? Id { get; set; } 

     public string FirstName { get; set; } 

     public string MiddleName { get; set; } 

     public string SecondName { get; set; } 

     public string PhoneNbr { get; set; } 

     public string Email { get; set; } 


     public virtual HashSet<SalesOrder> SalesOrder { get; set; } 

     internal class Config : EntityTypeConfiguration<Customer> 
     { 
      public Config() 
      { 

      } 
     } 
    } 
} 
+2

如果你使用EF,很会照顾它给你,如果你有你的模型的导航性能。 –

+0

其实你用EF来处理你的关系,你不需要得到最后的记录或范围... –

+0

我已经修改了问题并添加了控制器和实体类。 –

回答

3

两种方式:

  1. 保存客户实体,和Entity Framework将回填的PK属性与它的ID。然后,您可以将此用于订单实体。

    db.Customers.Add(customer); 
    db.SaveChanges(); 
    order.CustomerId = customer.Id; // has a value now 
    
  2. 只需通过导航属性将客户与订单关联即可。当您保存所有实体框架时,首先需要保存哪些关系,然后在相关实体中填写相应的FK ID。

    order.Customer = customer; 
    db.Orders.Add(order); 
    db.SaveChanges(); // customer is saved first and the id is set for order.CustomerId automatically 
    
+0

你能举个例子吗?我试图做到:AccountingRepository repository = new AccountingRepository(); repository.AddOrUpdate (customer); repository.Save(); repository.AddOrUpdate (salesOrder); repository.Save(); repository.Dispose(); //并没有帮助 –

+0

请参阅上面的更新。如果这不适用于您的存储库方法,则存储库中的某些内容不会正确设置。 –