2017-11-15 21 views
1

양쪽 끝에 필요한 FK와 순환 종속성 :EF 코어 2.0 - 나는 두 단체로 구성된 비교적 간단한 데이터 모델이

public class User 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public int CurrentLocationId { get; set; } 

    public List<Location> Locations { get; set; } 
    public Location CurrentLocation { get; set; } 
} 

순서에서 다음

public class Location 
{ 
    public int Id { get; set; } 
    [Required] 
    public int UserId { get; set; } 
    public string Address { get; set; } 

    public User User { get; set; } 
} 

성공적인 마이그레이션을 얻을 수 있습니다 실행하려면 다음 모델 빌더 코드가 필요합니다.

builder.Entity<Location>() 
     .HasOne(x => x.User) 
     .WithMany(x => x.Locations) 
     .HasForeignKey(x => x.UserId); 

이로 인해 데이터베이스가 I 기대하고 그것을 필요로하는 방법. 그러나 다음과 같은 순환 종속성 오류로 인해 엔티티를 저장할 수 없습니다.

InvalidOperationException : 순환 종속성이 저장할 데이터에서 감지되어 변경 사항을 저장할 수 없습니다 : 'ForeignKey : User {'CurrentLocationId '} - > 위치 { 'Id'} ToPrincipal : CurrentLocation, ForeignKey : 위치 { 'UserId'} -> 사용자 { 'Id'} ToDependent : 위치 ToPrincipal : 사용자 '.

EF Core 2.0에서이 문제를 해결할 방법이 있습니까?

필자는 데이터 모델을 변경하여 일주 할 수있는 몇 가지 옵션이 있지만 DB 제약 조건을 사용하여 모든 위치가 사용자에게 다시 연결되도록하고 모든 사용자가 CurrentLocation 집합을 가져야합니다. . 나는 그것이 문제를 해결할 것이지만 나는 CurrentLocation 필드에 실제로 null을 허용 할 수 없다는 것을 안다!

다음과 같이 내가 시도하고 저장하는 사용자가 사용하고있는 코드는 (데모 목적 간체)입니다

:

var location = new Location 
{ 
    Address = "Some address" 
}; 

_context.Locations.Add(location); 

var user = new User 
{ 
    Name = "Stu" 
}; 

_context.Users.Add(user); 

user.Locations = new List<Location> 
{ 
    location 
}; 

user.CurrentLocation = location; 

await _context.SaveChangesAsync(); 

와 나는 또한

var location = new Location 
{ 
    Address = "Some address" 
}; 

var user = new User 
{ 
    Name = "Stu", 
    Locations = new List<Location> 
    { 
     location 
    }, 
    CurrentLocation = location 
}; 

_context.Users.Add(user);  
await _context.SaveChangesAsync(); 

을 시도했다 그러나 오류가 남아 같은. 어떤 종류의 고급 ModelBuilder 재정의로이를 고칠 수 있습니까? 아니면 내 데이터 모델 변경/nulls 실제로 null을 허용해서는 안되는 허용?

미리 감사드립니다.

답변

0

내 질문에 대답하려면 - 그냥 확인하고 SQL 서버는 연기 가능한 제약 조건을 지원하지 않으므로 EF는 아무 일도 할 수 없습니다! 데이터 모델로 변경하십시오.

+1

주기없이 사용자를 삽입 할 수 있도록 최소로 User.CurrentLocationId를 null로 설정하십시오. –