简体   繁体   中英

How to add to an intermediary table in Entity Framework

I have the following entity:

class Car
{
    public string make;
    public string model;
    public string registration;
}

We have multiple dealerships and we want to ensure that dealer1 can only see cars that belong to them, and dealer2 can only see their cars.

We don't want to implement this check in the everyday business logic of our applications since it could lead to inconsistent enforcement of the rules, so I'm creating a thin wrapper around Entity Framework which does that.

I have another entity:

class Dealer
{
    public Guid id;
}

I don't want car to reference dealer, so instead I plan to have my wrapper code look like this:

void AddCar(Car car, Dealer dealer)
{
    // Some authorization logic goes here

    *Add dealer if not already added

    context.Add(car)

    *Add link between car and dealer to third table
}

Is there any way to add data to a third link table without defining a new class to represent that link for every type of entity? Eg can I just do like a dumb table insert or something like that?

I've tried to simplify my example as much as possible for clarity, but the reality is that I'm trying to make the wrapper generic as I have no idea what entities exist across all the micro services it will be used in (and nor should I)

You can execute SQL queries in entity framework by using ExecuteSql .

int carId = 1;
int dealerId = 1;
using (var context = new AppDbContext())
{
    var sql = $"INSERT INTO [CarDealer] ([CarId], [DealerId]) VALUES ({carId}, {dealerId})";
    var rowsModified = context.Database.ExecuteSql(sql);
}

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