sve*_*vit 9 c# sql-server orm dapper
在我之前的问题中略微更高级的映射:)
表:
create table [Primary] (
Id int not null,
CustomerId int not null,
CustomerName varchar(60) not null,
Date datetime default getdate(),
constraint PK_Primary primary key (Id)
)
create table Secondary(
PrimaryId int not null,
Id int not null,
Date datetime default getdate(),
constraint PK_Secondary primary key (PrimaryId, Id),
constraint FK_Secondary_Primary foreign key (PrimaryId) references [Primary] (Id)
)
create table Tertiary(
PrimaryId int not null,
SecondaryId int not null,
Id int not null,
Date datetime default getdate(),
constraint PK_Tertiary primary key (PrimaryId, SecondaryId, Id),
constraint FK_Tertiary_Secondary foreign key (PrimaryId, SecondaryId) references Secondary (PrimaryId, Id)
)
Run Code Online (Sandbox Code Playgroud)
类别:
public class Primary
{
public int Id { get; set; }
public Customer Customer { get; set; }
public DateTime Date { get; set; }
public List<Secondary> Secondaries { get; set; }
}
public class Secondary
{
public int Id { get; set; }
public DateTime Date { get; set; }
public List<Tertiary> Tertiarys { get; set; }
}
public class Tertiary
{
public int Id { get; set; }
public DateTime Date { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
是否可以使用一个选择来填充它们?像这样的东西:
const string sqlStatement = @"
select
p.Id, p.CustomerId, p.CustomerName, p.Date,
s.Id, s.Date,
t.Id, t.Date
from
[Primary] p left join Secondary s on (p.Id = s.PrimaryId)
left join Tertiary t on (s.PrimaryId = t.PrimaryId and s.Id = t.SecondaryId)
order by
p.Id, s.Id, t.Id
";
Run Code Online (Sandbox Code Playgroud)
然后:
IEnumerable<Primary> primaries = connection.Query<Primary, Customer, Secondary, Tertiary, Primary>(
sqlStatement,
... here comes dragons ...
);
Run Code Online (Sandbox Code Playgroud)
Edit1 - 我可以使用两个嵌套循环(foreach secondaries - > foreach tertiaries)来执行它,并对每个项执行查询,但只是想知道是否可以使用单个数据库调用来完成.
Edit2 - 也许QueryMultiple方法在这里是合适的,但如果我理解正确,那么我需要多个select语句.在我的实际例子中,select有超过20个条件(在where子句中),其中search参数可以为null,所以我不想重复所有查询中所有语句的所有条件...
Dapper 支持多重映射,文档请参见:http://code.google.com/p/dapper-dot-net/
这是我目前正在进行的项目之一的示例之一:
var accounts2 = DbConnection.Query<Account, Branch, Application, Account>(
"select Accounts.*, SplitAccount = '', Branches.*, SplitBranch = '', Applications.*" +
" from Accounts" +
" join Branches" +
" on Accounts.BranchId = Branches.BranchId" +
" join Applications" +
" on Accounts.ApplicationId = Applications.ApplicationId" +
" where Accounts.AccountId <> 0",
(account, branch, application) =>
{
account.Branch = branch;
account.Application = application;
return account;
}, splitOn: "SplitAccount, SplitBranch"
).AsQueryable();
Run Code Online (Sandbox Code Playgroud)
技巧是使用 splitOn 选项,将记录集划分为多个对象。
您还可以检查我的问题以查看上述示例的类结构:Dapper Multi-mapping Issue
归档时间: |
|
查看次数: |
5408 次 |
最近记录: |