使用Enterprise Library的ExecuteSprocAccessor方法和泛型 [英] Using Enterprise Library's ExecuteSprocAccessor method with generics

查看:178
本文介绍了使用Enterprise Library的ExecuteSprocAccessor方法和泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用.NET Enterprise Library的泛型的ExecuteSprocAccessor方法来使用一个类来处理数据库上的所有CRUD。在我的数据层中,我正在尝试如下所示:

I am trying to use one class to handle all of my CRUD on the database by using the ExecuteSprocAccessor method of the .NET Enterprise Library with generics. In my data layer, I was trying something like this:

public static class CRUDDatabase
{
    private static Database db = DatabaseFactory.CreateDatabase("ITS");

    public static T SelectSingle<T>(string sprocName, int id)
    {
        return db.ExecuteSprocAccessor<T>(sprocName, id).First();
    }
}

但是,我在返回行中遇到了构建错误在SelectSingle()方法中声明:

However, I get a build error on the return line in the SelectSingle() method that states:


'T'必须是一个具有公共无参数$ b的非抽象类型$ b构造函数以便将其用作通用
类型或方法中的参数'TResult'
'Microsoft.Practices.EnterpriseLibrary.Data.DatabaseExtensions.ExecuteSprocAccessor(Microsoft.Practices.EnterpriseLibrary.Data.Database,
string,params object [])'

SelectSingle()从数据库传入存储过程名称和所需对象的记录标识。最终我会有SelectAll(),Update(),Delete()等等。这些方法中的参数会有所不同,但您可以了解我正在努力完成的任务。

The idea behind the SelectSingle() method is that you pass in the stored procedure name and the record id of the object you want from the database. Eventually I would have SelectAll(), Update(), Delete(), etc. The parameters in those methods would be different, but you get the idea of what I'm trying to accomplish.

在阅读完这个错误之后,我开始认为这可能是不可能的,但是有谁知道这是否可行?此外,数据库中的字段与我的类中的字段匹配1:1,所以这就是为什么我没有指定任何映射器。

After reading that error, I am beginning to think this may be impossible, but does anyone know if this can work? Also, my fields in the database match 1:1 with the fields in my classes, so that is why I am not specifying any mappers.

谢谢

推荐答案

编译器告诉你什么是错误的:它期望一个类型的零参数公共构造函数。所有你交给它的是T,它不能作任何保证,所以它不会编译。

The compiler is telling you what's wrong: it's expecting a type that's got a zero-argument public constructor on it. All you've handed it is T, which it can't make any guarantees on, so it won't compile.

你需要添加一个通用约束来限制类型T可以。幸运的是,这非常简单:

You need to add a generic constraint to limit the types T can be. Luckily, that's trivially easy:

public static T SelectSingle<T>(string sprocName, int id)    
    where T : new()  // <---- here's the constraint
{
    return db.ExecuteSprocAccessor<T>(sprocName, id).First();    
}

它告诉编译器任何传入的类型必须有一个零参数构造函数。

That tells the compiler "Any type passed here must have a zero-argument constructor.

这篇关于使用Enterprise Library的ExecuteSprocAccessor方法和泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆