2017-12-13 24 views
1

내가 신원 프레임 워크에 정의 된 표준 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; 
} 
+0

EF가 추가하려고하는 엔티티는 무엇입니까? '도시? 엔티티 선언을 보여줄 수 있습니까? – GGO

+0

이 문제는 미리 첨부 된 부착 된 엔터티를 컨텍스트에 "추가됨"으로 표시 한 EF의 동작과 관련됩니다. 모든 관련 개체는 일정한 관계가있는 것 같기 때문에 관련 클래스를 분석을 위해 표시해야합니다 ('국가', '국가', '도시'및 '주소'). –

+0

'Address' 클래스의 코드를 보여줄 수 있습니까? –

답변

1

나는 오래 전에 비슷한 문제가 있었다. 나는 문제를 모르지만 나는 해결 방법이 있습니다

코드를 바꿉니다

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

아래 코드 :

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

이 올바르게 데이터를 저장됩니다.

+0

효과가 있습니다! 고맙습니다. –

0

문제는, 당신은 때마다 새로운 개체를 만드는 :

내 모델입니다. 먼저 테스트를 수행하여 사용자가 존재하는지 확인한 다음 개체가 기존 데이터로 채워지고 업데이트를 사용해야합니다. 따라서 UserManager.UpdateAsync 메서드를 사용하는 방법에 대해서도 생각해 볼 필요가 있습니다.

+0

이것은 등록 컨트롤러이기 때문에 실제로 새 개체를 만들고 있습니다. 새로운 사용자와 새 회사 및 새 UserProfile을 만듭니다. 그러나시는 db에서 적재됩니다. 왜 내가 그렇게해서는 안되는거야?! –

+0

엔티티가 이미 존재한다고하셨습니다. 존재한다면 업데이트를 수행하거나 전혀 수행 할 필요가 없습니다. 주소가 이미 존재하는 경우 사용자에 대해 새 주소 개체를 만들어서는 안됩니다. 대신 링크를 만들려면 주소의 ID를 사용자의 주소 ID에 지정해야합니다. – bilpor

+0

사용자 엔티티가 새 것입니다. 또한 Address는 User이지만 City, State 및 Country는 이미 데이터베이스에 있습니다. 내 질문을 검토하십시오. –