7

2 개의 간단한 테이블이 있습니다.클래스 맵퍼에서 dapper 맵과 일대일 매핑

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로지도 관계를 1 대 1로하고 싶습니다. 있을 수있다?

저의 목표는 리포지토리를 통해 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(); 
    }