开发者

Why won't entity framework allow me to do a .FindBy....()

开发者 https://www.devze.com 2022-12-13 15:36 出处:网络
I create a EDM using my database and saw that while it was able to make relations like Customers.First().开发者_StackOverflowOrders

I create a EDM using my database and saw that while it was able to make relations like

Customers.First().开发者_StackOverflowOrders

there is nothing like

Customer.First().Orders.FindOrderByOrderID()

Customer.First().Orders.FindOrderByOrderName()

etc.

Maybe I was expecting it to be like that and that's how it doesnt work and I will probably just have to LINQ to entities and create mangers that handle business logic in them.

or does LINQ to SQL do this?


You can use LINQ with the Orders property, like this:

var order = Customer.First().Orders.FirstOrDefault(o => o.OrderId == someId);

This will return null if there was no matching Order.


With LINQ to Entities you can do this. Such as the example SLaks posted above.

If you're feeling adventurous, it is possible to write a function to do this. Since Entity Framework knows which column is the primary key it is possible to write a function like GetEntityByPrimaryKey.

CodeProject has an article regarding the repository pattern and if you search for "SelectByKey" you'll see their implementation of that. I use something similar and find it very helpful.


The idea is that you can use LINQ to write more flexible queries. Note, however, that you could probably so something like FindOrderByOrderName in .NET 4.0 by creating your own dynamic type (not trivial), that responded to calls following this pattern by building a LINQ query automatically. You'd lose intellisense, of course, and I doubt it would be worth it, but it could be done.

0

精彩评论

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

关注公众号