3

我正在使用下面 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->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)

谁能指导我可能是什么问题

4

1 回答 1

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");
于 2012-09-16T16:35:56.420 回答