2013-02-20 67 views
0

我有2個EF實體:參考查找實體,而不增加新的一

public partial class CustomerEntity 
{ 
    public int CustomerId { get; set; } 
    public string CustomerName { get; set; } 
    public virtual ICollection<RoleEntity> Roles { get; set; } 
} 

public partial class RoleEntity 
{ 
    public int RoleId { get; set; } 
    public string RoleName { get; set; } 
} 

這是我的插入方法:

public int? InsertCustomer(CustomerEntity customer) 
{ 
    _context.CustomerEntities.Add(customer); 

    try 
    { 
     return _context.SaveChanges(); 
    } 
    catch (DbEntityValidationException exception) 
    { 
     return null; 
    } 
} 

這是方法來創建新的客戶:

public int CreateNewCustomer(string Name) 
{ 
    // Some mapping to CustomerEntity 
    var _customerEntity = new CustomerEntity 
    { 
     CustomerName = Name, 
     Roles = new List<RoleEntity> 
     { 
      new RoleEntity 
      { 
       RoleId = 1 
      } 
     } 
    }; 
    return InsertCustomer(_customerEntity); 
} 

RoleEntity是一個'查找'表,意味着它有預設記錄,並且永遠不會有新的記錄。

每次創建新的CustomerEntity時,它都會有一個或多個角色。如何插入新的CustomerEntity而不在數據庫中創建新角色? 上面的CreateNewCustomer方法將插入新的Customer以及數據庫中的新角色,而我只希望將新角色引用到數據庫中的現有角色(id爲1)的新客戶。

回答

1

您可以從您的_content中加載Role實體並將該對象分配給_customerEntity。

public int? InsertCustomer(CustomerEntity customer, int roleId) 
{ 
    var role =_context.Roles.Find(customer); 
    _customerEntity Roles = new List<RoleEntity>{ role }; 
    return _context.SaveChanges(); 
} 
1

剛取RoleEntity你要分配給客戶,並把它添加到客戶直接ICollection

+0

這不是我在上面的CreateNewCustomer()方法中做的嗎?這創造了新的角色以及新的客戶。我正試圖將現有角色與新客戶聯繫起來。 – stack247 2013-02-20 07:14:29

+0

當你說'新角色實體 {RoleId = 1 }',你正在表中創建新的條目。所以,而不是單獨查詢「RoleEntity」,並在那裏分配提取的對象。 – 2013-02-20 07:20:02

2

至於說,你可以從數據庫中加載的作用,並把它添加到客戶的Roles集合,但你也可以使用一個stub object「新」的角色(而無需使數據庫往返):

public int CreateNewCustomer(string Name) 
{ 
    var role = new RoleEntity { RoleId = 1 }; 
    AttachEntity(role); // role is "Unchanged" now 
    // Some mapping to CustomerEntity 
    var customerEntity = new CustomerEntity 
    { 
     CustomerName = Name, 
     Roles = new List<RoleEntity>{ role } // Will not set role to "Added" 
    }; 

    return InsertCustomer(customerEntity); 
} 

我假設CreateNewCustomer是在某種類型的存儲庫有一個DbContext實例。 AttachEntity沒有做任何事情,只是將實體附加到上下文中:

void AttachEntity<T>(T entity) 
{ 
    this._context.Set<T>().Attach(entity); 
}