7

У меня есть 2 простых стола.dapper map one to one in classmapper

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

В приложении I сопоставить эти таблицы для моделирования классов:

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 в классеmapper. Возможно?

Моя цель - это когда я добавил объект владельца, который также установил свойство Status to 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"); 

    } 
} 

Благодаря

ответ

8

Вы можете попробовать щеголеватый в 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(); 
    }