简体   繁体   中英

Calling SProcs from EF best practice

I have imported some stored procedures in to EF.

Only stored procedures will be used, no LINQ to Entities.

What are best practices for this?

I simply have a class that uses an Entities field to call the stored procedures:

public class DataAccess : IDataAccess
{
    private readonly MyEntities entities = new MyEntities();

    public IEnumerable<MyObj> GetMyObJects()
    {
        return entities.GETMyObj().Select(x => new MyObj { Name = x.NAME }).ToList();
    }

    public IEnumerable<MyObj2> GetMyObJects2()
    {
        return entities.GETMyObj2().Select(x => new MyObj2 { Name = x.NAME }).ToList();
    }

    public IEnumerable<MyObj3> GetMyObJects3()
    {
        return entities.GETMyObj3().Select(x => new MyObj3 { Name = x.NAME }).ToList();
    }
} 

Is this recommended? Should I be using a new Entities for every method?

As below:

public IEnumerable<MyObj3> GetMyObJects3()
{            
    using(MyEntities entities = new MyEntities())
    {
        return entities.GETMyObj3().Select(x => new MyObj3 { Name = x.NAME }).ToList();
    }
}

Julie Lerman撰写了一篇非常全面的文章,其中包含有关此主题的示例代码,它位于此处

Yes. what you have in your post is the recommended way, so you would have something like:

public IEnumerable<MyObj3> GetMyObJects3()
{            
    using(MyEntities entities = new MyEntities())
    {
        ObjectResult<SPResult> Results = entities.GetMyObJects3();
        IEnumerable<MyObj3> results = Results.ToList();

        return results;
    }
}

Using the EDMX file , create function imports. in this example GetMyObJects3() is the function import.

只要您的代码只从数据库中读取数据,我就不会发现任何问题。

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