Dapper:如何加载虚拟属性?

时间:2018-06-24 14:08:53

标签: c# sql dapper

我想获取一个itf

itf

(已加载Advert属性)

public class Advert
{
    public int ID { get; set; }
    public DateTime DateCreation { get; set; }
    public String Title { get; set; }
    public String Description { get; set; }
    public virtual Member Creator { get; set; }
}

具有以下功能:

Creator

但是我有以下错误:

  

InvalidCastException:无法将类型为“ System.Int32”的对象转换为“ Models.Member”。

错误的原因可能是什么?

1 个答案:

答案 0 :(得分:1)

根据查询,看起来像Advert.Creator类型的int列与模型上的Member Creator属性冲突。

将属性名称更改为其他名称,以避免名称冲突

public class Advert {
    public int ID { get; set; }
    public DateTime DateCreation { get; set; }
    public String Title { get; set; }
    public String Description { get; set; }
    public virtual Member Owner { get; set; }
}

并相应地更新查询

public Advert GetById(int id) {
    var connection = unitOfWork.Connection;
    String sql = 
    @"select * from Advert AS A
    inner join Member AS M on A.Creator = M.ID 
    where A.ID = @aid";
    var data connection.Query<Advert, Member, Advert>(
        sql, 
        (advert, member) => { advert.Owner = member; return advert; }, 
        new { aid = id }
    );
    return data.Single();
}

理想情况下,表中的Advert.Creator列应命名为CreatorId。这样可以使原始代码按需工作。