내가 신원 프레임 워크에 정의 된 표준 ApplicationUser 클래스를 정의하고있는 EF 6 코드 - 먼저 MVC 플러스 신원엔티티 프레임 워크는 기업이 이미 데이터베이스
을 사용하고 있습니다에 존재 삽입 난을 통해 새로운 사용자를 등록 할 때 내 웹 페이지에서 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와 같은 소리는 국가 엔터티를 db에 삽입하는 것과 같습니다. EF가 Address를 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;
}
EF가 추가하려고하는 엔티티는 무엇입니까? '도시? 엔티티 선언을 보여줄 수 있습니까? – GGO
이 문제는 미리 첨부 된 부착 된 엔터티를 컨텍스트에 "추가됨"으로 표시 한 EF의 동작과 관련됩니다. 모든 관련 개체는 일정한 관계가있는 것 같기 때문에 관련 클래스를 분석을 위해 표시해야합니다 ('국가', '국가', '도시'및 '주소'). –
'Address' 클래스의 코드를 보여줄 수 있습니까? –