【问题标题】:dapper map one to one in classmapperdapper 在 classmapper 中一对一映射
【发布时间】:2013-08-24 02:07:42
【问题描述】:

我有两张简单的桌子。

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),
);

在应用程序中,我将这些表映射到模型类:

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;}
}

我使用 dapper 和 dapper 扩展。

我想在 classmapper 中的 dapper 中一对一地映射关系。有可能吗?

我的目标是当我添加所有者对象时,该对象还通过存储库向数据库设置了属性状态 它还插入记录做状态表。

实现此行为的最佳方法是什么?

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");

    }
}

【问题讨论】:

    标签: foreign-keys dapper relation dapper-extensions


    【解决方案1】:

    你可以试试 Dapper 的 multi-mapping 功能:

    [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();
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-27
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2021-11-05
      • 2015-01-22
      • 2022-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多