开发者

Using Enterprise Library's ExecuteSprocAccessor method with generics

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();
    }
}

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

'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TResult' in the generic type or method 'Microsoft.Practices.EnterpriseLibrary.Data.DatabaseExtensions.ExecuteSp开发者_开发问答rocAccessor(Microsoft.Practices.EnterpriseLibrary.Data.Database, string, params object[])'

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.

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.

Thanks


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.

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜