尝试在dapper查询中映射多个对象时出错

时间:2012-09-16 05:00:35

标签: c# dapper

我正在使用下面的SQL中给出的表结构测试dapper

    CREATE TABLE [dbo].[Layer](
        [Name] [nvarchar](50) NOT NULL,
        [Key] [nvarchar](255) NULL,
        [FeatureColumn] [nvarchar](255) NULL,
        [Description] [nvarchar](255) NULL,
        [Defaults] [nvarchar](255) NULL,
        [Comments] [nvarchar](255) NULL,
        PRIMARY KEY  ([Name] ASC)
    )

    CREATE TABLE [dbo].[Theme](
        [Name] [nvarchar](50) NOT NULL,
        [IsDefault] [bit] NULL,
        [Field] [nvarchar](255) NULL,
        [Layer] [nvarchar](255) NULL,
        PRIMARY KEY  ([Name] ASC)
    )

用于在表格中生成数据的SQL

    INSERT INTO LAYER 
           (Name  ,[Key]   ,[Description]    ,Defaults,Comments)
    SELECT  'MOJO'  ,'ADM1','Administrative' ,'NULL'    ,'NULL'     UNION ALL
    SELECT  'Roads' ,'LID' ,'Roads'          ,'NULL'    ,'NULL'


    INSERT INTO Theme (Name,IsDefault,Field,Layer)
    SELECT 'M01',1,'ADM1','MOJO'

POCO对象是Layer和Theme,虽然我没有在SQL中提到它,但是Layer表和Theme表之间有一个关系Theme.Layer - >层

    public class Layer 
    {
        public virtual string Name { get; set; }
        public virtual string Key { get; set; }
        public virtual string Description{ get; set; }
        public virtual ICollection<Theme> Themes { get; set; }
        public virtual string Defaults { get; set; }
        public virtual string Comments { get; set; }

        public Layer()
        {
            Themes = new List<Theme>();
        }

    }

    public class Theme 
    {

        public virtual string Name { get; set; }
        public virtual bool IsDefault { get; set; }
        public virtual string Field { get; set; }
        public virtual Layer Layer { get; set; }

        public Theme()
        {
        }

    }

当我尝试在单个查询中映射图层和主题时出现以下错误,如:

    var sql = @"SELECT * FROM  Layer AS a LEFT OUTER JOIN
    Theme AS b ON a.Name = b.Layer";

    var k = conn.Query<Layer,Theme,  Theme>(
        sql,
        (a, b) => { a.Themes.Add(b); return a ; },
        splitOn: "Name"
        );

引发的例外是

   Error parsing column 9 (Layer=MOJO - String)

任何人都可以指导我这个问题是什么

1 个答案:

答案 0 :(得分:0)

问题是您的查询将Theme.Layer作为字符串返回,但在您的模型上将其映射为Layer类对象。解决此问题的一种方法是将查询更改为不返回该字段,因为它不需要,然后更新映射代码以将Layer属性设置为返回的图层对象。类似的东西:

var sql = @"SELECT a.*, b.Name, b.IsDefault, b.Field
            FROM  Layer AS a 
            LEFT OUTER JOIN Theme AS b ON a.Name = b.Layer";

var k = conn.Query<Layer, Theme, Layer>(sql, (a, b) =>
        {
            if (b != null)
                b.Layer = a;
            a.Themes.Add(b);
            return a;
        }, splitOn: "Name");