简体   繁体   中英

Refactoring LINQ statement using Entity Framework to a method

I have these Linq queries that I use multiple times in my code. I want to make a method of them and return their results.

var myevent = (from v in myEntities.Events
                           where _EventID == v.EventID
                           select v).SingleOrDefault();

var comments = (from c in myEntities.Fora
                            orderby c.DateCreated descending
                            where c.EventID == _EventID
                            select c).ToList();

Your question isn't very clear, but it sounds like you just want two methods to return the results of the linq query.

public Events GetEvent(int id)
{
    return (from v in myEntities.Events
           where _EventID == id
           select v).SingleOrDefault();
}

public List<Fora> GetComments(int id)
{
     return (from c in myEntities.Fora
             orderby c.DateCreated descending
             where c.EventID == id
             select c).ToList();
}

Your question has too many unknowns to answer concretely, and this is something the SO is particular about.

I'm going to assume your entity is DB-backed.

You need to be aware of the transaction scope. You could use a separate class with a static "myEntities" and implement as Anonymous above. However if different threads are calling in you may end up with a nested transaction. You also don't want to create a new connection every time you call it.

I would implement this as part of a broader data access layer and pass your connection to it as part of the constructor. If you choose to use a static method then you should pass the connection as one of the params.

Or you could have an abstract class with this logic, and have child classes implement it.

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