Dapper C#:将列对象拆分为TypeID和TypeName

时间:2017-06-12 09:03:27

标签: dapper

我正在使用短小精悍并希望拆分

Class EType
{
    int TypeID;
    string TypeName;
}

Class Employee
{
    int id;
    string location;
    EType EmpType;
}

员工表:

ID||Location||TypeID||TypeName

在使用Dapper的CRUD操作期间,我希望自动将EmpType转换为DB中的各个列.Tried类型处理程序和自定义映射。但没有运气:(。

请帮忙吗?

1 个答案:

答案 0 :(得分:0)

首先,您必须使用属性,而不是字段。然后使用Dapper的multi-mapping

public class Employee
{
    public int Id { get; set; }
    public string Location { get; set; }
    public EType EType { get; set; }
}

public class EType
{
    public int TypeId { get; set; }
    public string TypeName { get; set; }
}

[TestFixture]
public class MultimappingTest
{
    [Test]
    public void TestSplit()
    {
        using (var conn = new SqlConnection(@"Data Source=.\sqlexpress;Integrated Security=true; Initial Catalog=foo"))
        {
            var result =
                conn.Query<Employee, EType, Employee>(@"select Id = 1, Location = 'earth', TypeId = 2, TypeName = 'human'",
                    (employee, type) =>
                    {
                        employee.EType = type;
                        return employee;
                    }, splitOn: "TypeId").First();

            Assert.That(result.EType.TypeId == 2);
            Assert.That(result.EType.TypeName == "human");
        }
    }
}