2013-02-20 49 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); 
}