首页 \ 问答 \ 使用EF的常见LINQ方法(Common LINQ method using EF)

使用EF的常见LINQ方法(Common LINQ method using EF)

所以这可能是一个愚蠢的问题,但我仍然不确定实体框架对象是如何工作的。 我在MVC3应用程序中使用EF4,并且有两个控制器需要对它使用相同的LINQ查询。 是否最好使用通过ref获取db实体的静态方法,或者该方法是否应该为其自己的实体使用“using”块(如本问题所示 )?

我认为使用块会增加额外的开销,但我没有找到其他方法的任何示例。 是否有适当的方法为EF访问制作“库”方法?


So this is probably a stupid question, but I am still not exactly sure how the entity frameworks objects work. I am using EF4 in an MVC3 app, and have two controllers that need to use the same LINQ query against it. Is it best to use a static method that takes the db entity by ref, or should the method use a "using" block for its own entity (as seen in this question)?

I would think the using block would add additional overhead, but I didn't find any examples of the other method. Is there a proper way to make "library" methods for EF access?


原文:https://stackoverflow.com/questions/6669178
更新时间:2023-09-30 20:09

最满意答案

正如您已经看到的那样,无法将BusClient传递给AddToClients 。 您必须通过复制非常难看的属性从Insert方法中的BusClient创建Client

public void Insert()
{
    using(MyBIEntities db = new MyBIEntities())
    {
        Client client = new Client();

        client.CityId = this.CityId;
        client.Name = this.Name;
        client.RegisterDate = this.RegisterDate;

        db.AddToClients(client);
        db.SaveChanges();
    }
}

重新思考设计。 从实体( Client )派生类( BusClient ),我看不到任何好处。 如果您无法更改Client类,则可以创建扩展方法...

public static class Extensions
{
    public static bool Validate(this Client client)
    {
        // Run validation rules on client object
    }
}

...或用于验证的单独类:

public class Validator
{
    public bool Validate(Client client)
    {
        // Run validation rules on client object
    }
}

我也会考虑这个单独的Insert方法。 虽然这可能在您的示例中起作用,但只要您必须操纵更复杂的对象图,它就会导致麻烦(或至少变得无用)。 在这种情况下,您将需要一个ObjectContext用于整个操作。 对于每个INSERT,UPDATE或DELETE,您不能再使用单独的ObjectContext工作了。

因此,我建议从特殊类中删除DB操作并将其放入主例程中。 整个事情可能看起来像:

try
{
    using(MyBIEntities db = new MyBIEntities())
    {
        Client client = new Client();

        client.CityId = int.Parse(ddlCity.SelectedValue());
        client.Name = txtName.Text;
        client.RegisterDate = Convert.ToDateTime("txtDate.Text");

        if (client.Validate())
        // works with the extension method, or with the Validator use:
        // Validator validator = new Validator();
        // if (validator.Validate(client))
        {
            db.AddToClients(client);
            db.SaveChanges();
        }
    }
}
catch (Exception ex)
{
    //Catching errors
}

在此示例中, BusClient类不再存在。


As you already have seen you cannot pass in a BusClient into AddToClients. You would have to create a Client from the BusClient in your Insert method by copying the properties which is quite ugly:

public void Insert()
{
    using(MyBIEntities db = new MyBIEntities())
    {
        Client client = new Client();

        client.CityId = this.CityId;
        client.Name = this.Name;
        client.RegisterDate = this.RegisterDate;

        db.AddToClients(client);
        db.SaveChanges();
    }
}

Rethink the design. I cannot see a benefit with deriving a class (BusClient) from an Entity (Client). If you cannot change the Client class you could create either an extension method ...

public static class Extensions
{
    public static bool Validate(this Client client)
    {
        // Run validation rules on client object
    }
}

... or a separate class for your validation:

public class Validator
{
    public bool Validate(Client client)
    {
        // Run validation rules on client object
    }
}

I would also think twice about this separate Insert method. While this may work in your example it can cause trouble (or at least become useless) as soon as you have to manipulate a more complex object graph. In such a case you will need one single ObjectContext for the whole operation. You cannot work then anymore with a separate ObjectContext for each INSERT, UPDATE or DELETE an so on.

So, I'd recommend to remove the DB operations from your special class and put this into the main routine. The whole thing could then look like:

try
{
    using(MyBIEntities db = new MyBIEntities())
    {
        Client client = new Client();

        client.CityId = int.Parse(ddlCity.SelectedValue());
        client.Name = txtName.Text;
        client.RegisterDate = Convert.ToDateTime("txtDate.Text");

        if (client.Validate())
        // works with the extension method, or with the Validator use:
        // Validator validator = new Validator();
        // if (validator.Validate(client))
        {
            db.AddToClients(client);
            db.SaveChanges();
        }
    }
}
catch (Exception ex)
{
    //Catching errors
}

The BusClient class doesn't exist anymore in this example.

相关问答

更多
  • 你的DAL类是用户区定义的 - 在PHP中没有这样的东西。 在某处发布它的整个代码,有人可能会告诉你如何处理它。 但是,我会根据你所说的提供泛型。 static::get_instance()以及你无法触发多个实例的提示表明你的数据库抽象层实际上是一个Singleton 。 这很好,然后再次,这是非常糟糕的。 Singleton的整个目标是将类限制为仅一个实例,这对于数据库层来说非常好。 但是,在您的情况下,您似乎希望同时连接到多个DB。 根据代码的编码方式,您可以在几乎不修改代码的情况下执行此操作。 作为 ...
  • 这种方法在BAL中。 假设sDal是定义某些方法的类的对象,则可以这样调用。 public intgetSomething(string getUserID) { int i = sDal.something(getUserID); return i; } this method is in BAL . Assuming sDal is the object of the class where something method is defined you can call like t ...
  • 众所周知,单身对象很难测试。 我将以这样的方式创建您的DAL,即实例化然后根据需要创建新的DAL并不昂贵。 这样您就可以更轻松地为DAL编写单元测试,但仍然不会产生太多开销。 此外,如果您将DAL创建为单例,那么如果您在多线程环境(例如Web应用程序)中使用它,则需要更加关注如何使其成为线程安全的。 Singleton objects are notoriously hard to test. I would look at creating your DAL in such a way that it i ...
  • 您返回false表示存在异常。 不建议这样做。 重新抛出它 catch(Exception e) { //blah, maybe add some useful text to e throw; } finally { //close up shop Although, look up what using does first incidentally } 然后处理它( catch (Exception e) { MessageBox.Show(("Error: " + e.Message)) ...
  • 最好的方法是: 不要自己动手,除非它是一个学术研究项目,或者你打算建立一个商业运输ORM。 首先尝试使用数十种现有的ORM解决方案。 (实体框架,亚音速,nhibernate等等)。 他们都有他们的怪癖和局限性,混杂着许多令人敬畏的东西。 ORM难以置信地做出巨大的承诺。 略有关系和金钱: http : //wekeroad.com/2009/06/11/youre-not-your-data-access/ Best approach is: Don't do it yourself unless its ...
  • 正如您已经看到的那样,无法将BusClient传递给AddToClients 。 您必须通过复制非常难看的属性从Insert方法中的BusClient创建Client : public void Insert() { using(MyBIEntities db = new MyBIEntities()) { Client client = new Client(); client.CityId = this.CityId; client.Na ...
  • 我认为您的团队负责人需要承诺一致性或花一些时间在ORM研究项目上提出建议使用。 换句话说,不一致和固定的团队负责人不应该担任该角色。 其次,出于多种原因,我倾向于同意您的DBA。 只要他/她足够灵活,就知道动态SQL有时会更好地解决问题。 根据您的具体情况,我要求您的DBA制定法律,每次都要使用存储过程,除非根据具体情况提供理由,并通过政策和监控来实施。 这将解决一致性问题。 也许那时候,有了这个政策,ORM看起来比将所有东西都手工编写给团队负责人更有吸引力。 I think your Team Lead ...
  • 我认为没有一个通用的解决方案,但是,如果你有一个简单的应用程序,你可能不希望不必要地使事情复杂化如果你能够保持数据上下文打开你的表示层,保留L2SQL实体有一些“生产力”增益: 支持延迟加载(虽然注意1:N问题) 您有一组生成的实体(尽管可以识别datacontext) 但是,对于更重,更纯粹的架构,您可以考虑 将Linq2SQL工件包装在存储库模式中 将L2SQL实体映射到POCO,然后将它们返回到BLL / Service Tier 根据您的网络和表示体系结构,您可能还需要考虑您的实体在网络上的样子(序 ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。