As said, you could load the role from the database and add it to the customer's Roles
collection, but you can also use the "new" role as a stub object (without the need to make a database roundtrip):
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);
}
I assume CreateNewCustomer
is in some kind of repository having a DbContext
instance. AttachEntity
does nothing but attach the entity to the context:
void AttachEntity<T>(T entity)
{
this._context.Set<T>().Attach(entity);
}