Dapper 连表查询

实体类:

UserInfo:

public partial class UserInfo
    {
        public UserInfo()
        {
            this.Persion = new HashSet<Persion>();
            this.MyTYC = new HashSet<MyTYC>();
        }
    
        public int id { get; set; }
        public string name { get; set; }
        public Nullable<System.DateTime> createTime { get; set; }
        public Movies Movies { get; set; }
        public virtual ICollection<MyTYC> MyTYC { get; set; }
    }

Movies:(跨库表)

public class Movies
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public string ReleaseDate { get; set; }
        public string Genre { get; set; }
        public string Price { get; set; }
        public UserInfo UserInfo { get; set; }

    }

MyTYC

public partial class MyTYC
    {
        public int id { get; set; }
        public string name { get; set; }

    }


代码:

string sql = @"select * from UserInfo u 
inner join [Movies].dbo.Movies m on u.id=m.ID 
inner join MyTYC t on u.id=t.id";
            var data = conn.Query<UserInfo, Movies, MyTYC, UserInfo>(sql, (u, m, t) => { u.Movies = m; u.MyTYC.Add(t); return u; });

主要是  
u.Movies = m

u.MyTYC.Add(t)
一个是关联主键表(单个对象),一个是关联外键表(集合)。




原文地址:https://www.cnblogs.com/hanjun0612/p/9779878.html