代码之家  ›  专栏  ›  技术社区  ›  flofreelance

如何加载虚拟属性?

  •  1
  • flofreelance  · 技术社区  · 6 年前

    我想找回一个 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 已加载属性)

    public class Member
    {
        public int ID { get; set; }
        public String Name { get; set; }
        public String Email { get; set; }
        public String Password { get; set; }
    }
    

    具有以下功能:

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

    但我有以下错误:

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

    错误的原因可能是什么?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Nkosi    6 年前

    根据查询,它看起来像 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();
    }
    

    理想情况下 广告创作者 表中的列应该是name CreatorId .这将允许原始代码按需要工作。