我有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)的新客戶。
這不是我在上面的CreateNewCustomer()方法中做的嗎?這創造了新的角色以及新的客戶。我正試圖將現有角色與新客戶聯繫起來。 – stack247 2013-02-20 07:14:29
當你說'新角色實體 {RoleId = 1 }',你正在表中創建新的條目。所以,而不是單獨查詢「RoleEntity」,並在那裏分配提取的對象。 – 2013-02-20 07:20:02