2017-12-01 13 views
2

내 데이터 모델은 현재 매우 간단합니다. 당신에게는 식당이 있고 식당도 있습니다. 사이에 '리뷰'라고하는 많은 관계가 있습니다.Entity Framework - 탐색 속성을로드 할 필요없이 행을 여러 테이블에 추가

리뷰를 데이터베이스에 추가하려면 리뷰 오브젝트를 저장하기 전에 사용자 오브젝트와 레스토랑 오브젝트를 검색해야합니다. 이것은 다음 코드로 수행됩니다

// The 'review' object is the object coming as parameter. 
var restaurant = await _context.Restaurants.FindAsync(review.RestaurantId); 
var user = await _context.Users.FindAsync(review.UserId); 

var newReview = _context.Reviews.Add(new DataService.Entities.Review 
{ 
    // setting other values 
    Restaurant = restaurant, 
    User = user 
}).Entity; 

await _context.SaveChangesAsync(); 

Review 클래스는 다음과 같습니다

public class Review 
{ 
    // Other properties... 
    public User User { get; set; } 
    public Restaurant Restaurant { get; set; } 
} 

그리고 모두 내 사용자와 레스토랑 클래스는 리뷰의 목록이 포함되어 있습니다.

네비게이션 속성으로 설정하기 위해 두 개체를 모두로드하고 싶지 않으므로이 방법을 사용하는 것이 더 좋습니다. 나는 단지 어떻게해야할지 모른다.

.Net Core 2.0 및 Entity Framework Core를 사용하고 있습니다.

답변

2
public class Review 
{ 
    [Key] 
    public int ReviewId { get; set; } 

    // Other properties... 
    [ForeignKey("User")] 
    public int UserId{get; set;} 
    public User User { get; set; } 

    [ForeignKey("Restaurant ")] 
    public int RestaurantId {get; set;} 
    public Restaurant Restaurant { get; set; } 
} 

그런 식으로, 당신은 단지

+0

하지만 나는 그것이 유창 API를 사용하여 수도 있는지 알고 싶어? – RandomStranger

1

만약 내가 제대로 이해하고, 엔티티 클래스 Review은 참고 탐색을 포함하는 사용자 아이디를 설정하고 RestaurantId, 당신은 사용자 또는 레스토랑 자신을로드 할 필요가 없습니다 수 명시 적 FK 속성이없는 속성

EF 코어는 FK를 나타내는 Shadow Properties을 가져 오거나 설정할 수 있기 때문에 그래도 질문하는대로 할 수 있습니다 (조금 특이한 방법 임에도 불구하고). 샘플의 경우

는이 같은 것입니다 : 이것은 가장 확실히 작동합니다

var entry = _context.Reviews.Add(new DataService.Entities.Review 
{ 
    // setting other values 
}); 
entry.Property("UserId").CurrentValue = review.UserId; 
entry.Property("RestaurantId").CurrentValue = review.RestaurantId; 

await _context.SaveChangesAsync();