简体   繁体   中英

Entity Framework - Adding row many to many table without having to load navigational properties

My data model is very simple currently. You have users, and you have restaurants. In between is a many to many relationship called 'Reviews'.

When I want to add a review to the database, I have to retrieve a user object and a restaurant object before I can save the review object. This is done with the following code:

// 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();

My Review class looks like this:

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

And both my user and restaurant class contain lists of reviews.

I'm pretty sure there is a better way to do this, since I don't want to load both objects just to set as navigational properties. I just don't know how to.

I'm using .Net core 2.0 and 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; }
}

That way, you can just set the UserId, and RestaurantId, and you don't have to load the User or Restaurant themselves

If I understand correctly, the entity class Review contains only reference navigation properties with no explicit FK properties.

Still it's possible to do what you are asking because EF Core allows you to get/set Shadow Properties representing the FKs (although in a bit unusual way).

In your sample case it would be something like this:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM