目前我的数据模型非常简单。你有用户,你有餐馆。两者之间是一种称为“评论”的多对多关系。
当我想向数据库添加评论时,我必须先检索用户对象和餐厅对象,然后才能保存评论对象。这是通过以下代码完成的:
// 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。
最佳答案
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; }
}
这样,您只需设置 UserId 和 RestaurantId,而不必自己加载 User 或 Restaurant
关于c# - Entity Framework - 添加行多对多表而无需加载导航属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47598073/