imo*_*din 7 foreign-keys relation dapper dapper-extensions
我有2个简单的表.
create table Owner
(
Id int primary key,
Name nvarchar(100),
);
create table Status
(
Id int primary key,
BrandName nvarchar(50)
OwnerId int foreign key references Owner(Id),
);
Run Code Online (Sandbox Code Playgroud)
在应用程序中,我将这些表映射到模型类:
public class Owner
{
public int Id {get;set;}
public string Name{get;set;}
public Status Status {get;set;}
}
public class Status
{
public int Id {get;set;}
public string Brand {get;set;}
public int OwnerId {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
我用dapper和dapper扩展.
我想在classmapper中的dapper中一对一地映射关系.这是可能的?
我的目标是当我添加所有者对象时,它还通过存储库设置了属性Status到db,它还插入了记录执行状态表.
实现这种行为的最佳方法是什么?
public class OwnerMapper : ClassMapper<Owner>
{
public OwnerMapper()
{
Table("Owner");
Map(p=>p.Id).Column("Id").Key(KeyType.Assigned);
Map(p=>p.Name).Column("Name");
//how map property status
}
}
public class StatusMapper : ClassMapper<Status>
{
public StatusMapper()
{
Table("Status");
Map(p=>p.Id).Column("Id").Key(KeyType.Identity);
Map(p=>p.Brand).Column("BrandName");
Map(p=>OwnerId).Column("OwnerId");
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢
Voi*_*Ray 12
您可以尝试Dapper的多映射功能:
[Test]
public void MyTest()
{
var connection = new SqlConnection("conn string here");
connection.Open();
const string sql =
"select Id = 1, Name ='Bill Gates', Id = 1, Brand = 'Apple', OwnerId = 1";
var result = connection.Query<Owner, Status, Owner>(sql,
(owner, status) =>
{
owner.Status = status;
return owner;
},
commandType: CommandType.Text
).FirstOrDefault();
Assert.That(result, Is.Not.Null);
Assert.That(result.Status, Is.Not.Null);
Assert.That(result.Status.Brand, Is.EqualTo("Apple"));
connection.Close();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10301 次 |
| 最近记录: |