gpt4 book ai didi

c# - 使用 Dapper 查询复杂对象

转载 作者:太空狗 更新时间:2023-10-29 20:06:58 24 4
gpt4 key购买 nike

我有一个具有以下属性的 Customer 类:

public int Id { get; set; }
public string Name { get; set; }
public int AddressId { get; set; }
public Address Address { get; set; }

我的目标是编写一个 Dapper 查询,该查询将使用内部联接来填充每个返回的客户中的整个地址属性。

这是我所拥有的,它正在工作,但我想知道这是否是最干净/最简单的方法:

StringBuilder sql = new StringBuilder();
using (var conn = GetOpenConnection())
{
sql.AppendLine("SELECT c.Id, c.Name, c.AddressId, a.Address1, a.Address2, a.City, a.State, a.ZipCode ");
sql.AppendLine("FROM Customer c ");
sql.AppendLine("INNER JOIN Address a ON c.AddressId = a.Id ");

return conn.Query<Customer, Address, Customer>(
sql.ToString(),
(customer, address) => {
customer.Address= address;
return userRole;
},
splitOn: "AddressId"
).ToList();
}

我对添加另一个属性有些担心,例如:

public Contact Contact { get; set; }

我不确定如何切换上面的语法来填充地址和联系人。

最佳答案

我使用 Dapper 1.40 版进行编码,并且编写了如下所示的查询,我没有任何问题可以填充一个以上的对象,但我遇到了 8 个我可以映射的不同类的限制一个问题。

public class Customer {
public int Id { get; set; }
public string Name { get; set; }
public int AddressId { get; set; }
public int ContactId { get; set; }
public Address Address { get; set; }
public Contact Contact { get; set; }
}

public class Address {
public int Id { get; set; }
public string Address1 {get;set;}
public string Address2 {get;set;}
public string City {get;set;}
public string State {get;set;}
public int ZipCode {get;set;}
public IEnumerable<Customer> Customer {get;set;}
}

public class Contact {
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<Customer> Customer {get;set;}
}

using (var conn = GetOpenConnection())
{
var query = _contextDapper
.Query<Customer, Address, Contact, Customer>($@"
SELECT c.Id, c.Name,
c.AddressId, a.Id, a.Address1, a.Address2, a.City, a.State, a.ZipCode,
c.ContactId, ct.Id, ct.Name
FROM Customer c
INNER JOIN Address a ON a.Id = c.AddressId
INNER JOIN Contact ct ON ct.Id = c.ContactId",
(c, a, ct) =>
{
c.LogType = a;
c.Contact = ct;
return c;
}, splitOn: "AddressId, ContactId")
.AsQueryable();

return query.ToList();
}

关于c# - 使用 Dapper 查询复杂对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44980945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com