![](/img/trans.png)
[英]Entity Framework 6 - Multiple lookup inserts vs An object with the same key already exists in the ObjectStateManager
[英]Entity Framework Inserts the entity Already Exists in Database
我正在使用EF 6 Code-First MVC和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加载“城市”。 所以我尝试使用下面的代码,但没有帮助:
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;
}
问题是,您每次都在创建新对象。 您需要先执行测试以查看用户是否存在,如果存在,然后使用现有数据填充对象并使用Update。 因此,您还需要考虑使用UserManager.UpdateAsync
方法。
很久以前我也遇到过类似的问题。 我不知道问题所在,但是有一种解决方法:
替换代码:
var result = await UserManager.CreateAsync(user, model.Password);
使用以下代码:
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
var result = UserManager.Create(user, model.Password);
这样可以正确保存数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.