문제

I have 2 EF Entities:

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; }
}

This is my insert method:

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

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

This is method to create new customer:

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);
}

The RoleEntity is a 'lookup' table, means it has preset records and will never have new one.

Everytime new CustomerEntity is created, it will have one or more role. How can I insert new CustomerEntity without creating new Role in database? My CreateNewCustomer method above will insert new Customer as well as new Role in database while I only want new Customer whose role reference to existing Role in database (with id 1).

도움이 되었습니까?

해결책 2

You could load the Role entity from your _content and assign the object to the _customerEntity.

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

다른 팁

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);
}

Just fetch the RoleEntity you want to assign to that customer and add it to the customer ICollection directly.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top