我正在尝试使用 Dapper 与 ASP.NET SQL Membership Provider 表进行交互.我包装了 SqlMembershipProvider 类,并添加了一个额外的方法,根据与我拥有的一些自定义表相关的特定条件来获取 MembershipUsers.
I'm trying to use Dapper to interface with the ASP.NET SQL Membership Provider tables. I wrapped the SqlMembershipProvider class and added an additional method to get me the MembershipUsers given a certain criteria relating to some custom tables I have.
当使用 Dapper 查询数据时,似乎 Dapper 首先使用无参数构造函数实例化类,然后将返回的列映射"到对象的属性中.
When querying the data with Dapper, it appears that Dapper first instantiates the class with a parameter-less constructor, and then "maps" the returned columns into the properties on the object.
但是,MembershipUser 类的 UserName 属性没有设置器.从 Dapper SqlMapper.cs 的 1417 行左右来看,方法 GetSettableProps() 只获取可设置的属性.
However, the UserName property on the MembershipUser class has a no setter. Judging from around line 1417 in the Dapper SqlMapper.cs, the method GetSettableProps() only gets settable properties.
我尝试执行 MultiMap 查询来调用构造函数,但问题是传递给查询的对象已经缺少用户名.
I tried to do a MultiMap query to invoke the constructor, but the problem with that is the objects passed into the query are already missing the UserName.
我猜我可以修改 GetSettableProps() 方法,但我不确定这是否有效,或者它是否会影响我现有的代码.
I'm guessing I could modify the GetSettableProps() method, but I'm not sure if that will work, or if it will affect my existing code.
我是否可以调用 MembershipUser 类具有的自定义构造函数?
或者我可以对 Dapper 做出合理的改变来支持我的情况吗?
** 更新 **
Marc 使用非通用/动态 Query() 方法的回答是正确的,但对于后代,这是我在 Dapper 中所指的方法:
Marc's answer to use the non-generic/dynamic Query() method was correct, but for posterity, this is the method I was referring to inside Dapper:
static List<PropInfo> GetSettableProps(Type t) { return t .GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .Select(p => new PropInfo { Name = p.Name, Setter = p.DeclaringType == t ? p.GetSetMethod(true) : p.DeclaringType.GetProperty(p.Name).GetSetMethod(true), Type = p.PropertyType }) .Where(info => info.Setter != null) .ToList(); } 推荐答案我会在这里使用非通用查询 API...
I would use the non-generic Query API here...
return connection.Query(sql, args).Select(row => new AnyType((string)row.Foo, (int)row.Bar) { Other = (float)row.Other }).ToList();使用它,您可以使用非默认构造函数和属性赋值,无需任何更改,将动态"用作中间步骤.
Using this you can use both non-default constructors and property assignments, without any changes, by using "dynamic" as an intermediate step.
更多推荐
使用 Dapper 调用自定义构造函数?
发布评论