我有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