开发者

EF Insert Many Entities Based on User Selections

开发者 https://www.devze.com 2023-03-21 17:21 出处:网络
We have an ASP .NET MVC application that allows users to provide a set of filter criteria that are logically ANDed together. The result of this is to graphically show the user how many items match tho

We have an ASP .NET MVC application that allows users to provide a set of filter criteria that are logically ANDed together. The result of this is to graphically show the user how many items match those criteria. The user can then accept those criteria to create a set of entities in another table.

This is the intuitive and, IMO, sloppy approach:

// where "context" is an EF Context...
foreach (var person in allMatchingPeople) {
    context.MailRequest.Add(new MailRequest 开发者_高级运维{
        Person = person
    });
}

context.SaveChanges();

I don't like that it's iterative. If it were SQL I could just do something like:

INSERT INTO MailRequest (PersonId)
SELECT Id
FROM Person
WHERE ... -- filter by criteria provided from user input


In such case use stored procedure EF doesn't offer such functionality.


You can write it like this

allMatchingPeople.ForEach(p => context.MailRequest.Add(p));
0

精彩评论

暂无评论...
验证码 换一张
取 消