实体框架插入实体已存在于数据库中

时间:2017-12-13 08:59:28

标签: c# asp.net-mvc entity-framework entity-framework-6

我正在使用EF 6 Code-First MVC plus Identity

我已经定制了Identity框架中定义的标准ApplicationUser类,当我尝试通过我的网页注册新用户时,EF会尝试插入已存在于数据库中的实体。

//some code above here

using (ApplicationDbContext db = new ApplicationDbContext())
{
    // I load the City object form db based on the model passed to current method
    City city = db.Countries.Include("States.Cities")
        .First(c => c.Code == model.CountryCode)
        .States.First(s => s.Id == model.StateId)
        .Cities.First(ci => ci.Name == model.CityName);

    // I create a new Employee and a new Company and Company has an Address 
    // referring to the City I loaded from db
    Employee employee = new Employee
    {
        FirstName = model.FirstName,
        LastName = model.LastName,
        Company = new Company
        {
            Name = model.CompanyName,
            OfficePhone = model.OfficePhone,
            Address = new Address { City = city, Street = model.Street, ZipCode = model.ZipCode }
        }
    };

    // This is part of Identity framework code
    var user = new ApplicationUser
    {
        UserName = model.Email,
        Email = model.Email,
        // my custom code: I assign employee to the standard ApplicationUser class
        UserProfile = employee
    };

    // This is going to save the new user to database, 
    // but it tries to insert a new Country object into db. 
    // Note that City class has a property of type State 
    // and State class has a property type of Country 
    var result = await UserManager.CreateAsync(user, model.Password);

    // more code below

根据我得到的错误,听起来像EF正在将国家/地区实体插入数据库。我想这会在EF向db添加地址时发生。在我的代码中,Address是新对象,但是City,State和Country已经存在,你看到我在开始时从db加载City。所以我尝试使用下面的代码,但它没有帮助:

db.Entry(employee.Company.Address.City).State = EntityState.Unchanged;

对于冗长的代码感到抱歉,我试图尽量减少这个。

这是我的模特:

public class Country
{
    string Code;
    string Name;
    List<State> States;
}

public class State
{
    int Id;
    string Name;
    List<City> Cities;
}

public class City
{
    int Id;
    string Name;
    State State;
}

public class Address
{
    string Street;
    string ZipCode;
    City City;
}

public class Company
{
    string Name;
    string OfficePhone;
    Address Address;
}

2 个答案:

答案 0 :(得分:0)

问题是,您每次都在创建新对象。您需要首先执行测试以查看用户是否存在,如果存在,则使用现有数据填充对象并使用Update。所以你还需要考虑使用UserManager.UpdateAsync方法。

答案 1 :(得分:0)

我有很久以前的类似问题。我不知道问题,但我有一个解决方法:

替换代码:

var result = await UserManager.CreateAsync(user, model.Password);

以下代码:

var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
var result = UserManager.Create(user, model.Password);

这将正确保存数据。