1

我正在使用 Dapper 和 MySql 来获取具有多重映射的 uTeacher 列表,但我无法让它工作!我从 Int32 到 uDepartement 类和其他类的 Invalid Cast 异常!

(DataException:解析第 33 列时出错(Department=1 - Int32))

我有以下课程:

public class uTeacher : uPerson
{
        public uTeacher() { } 

        public uPosition Position { get; set; }
        
        public uFaculty Faculty { get; set; }

        public uDepartment Department { get; set; }

        public IList Modules { get; set; }
}

+--uTeacher------------+
| int Id
| ....
| uDepartment Department
| uPosition Position
| uFaculty Faculty
| IList Modules
+---------------------

+-uDepartment -+    +--uPosition --+   +--uFaculty --+   +--uModule--+
| int Id            | int Id           | int Id          | int Id
| ...               | ...              | ...             | ...
| IList Teachers    | IList Teachers   | IList Teachers  | uTeacher Teacher 
+--------------

我的 GetAll 方法:

public Task<IEnumerable<uTeacher>> GetAllAsync()
        {
            var select = $@"select * 
                        from uTeacher t
                        left join uDepartement d on d.Id = t.Department 
                        left join uPosition p on p.Id = t.Position
                        left join uFaculty f on f.Id = t.Faculty
                        left join uModule m on m.Teacher = t.Id ";    //many

            var result =
                Connection.QueryAsync<uTeacher, uDepartment, uPosition, uFaculty, uModule, uTeacher>(
                    select, (t, d, p, f, m) =>
                    {
                        t.Department = d;
                        t.Position = p;
                        t.Faculty = f;
                        t.Position = p;
                        t.Modules.Add(m);
                        return t;
                    }, splitOn: "Id,Id,Id");
            return result;
        }

我喜欢使用 dapper,但我被困在这里,我花了很多时间在这上面,不知道发生了什么。

编辑

当我在没有映射的情况下运行它时,我得到了同样的异常

public Task<IEnumerable<uTeacher>> GetAllAsync(){
return Connection.QueryAsync<uTeacher>("Select * from univteacher");
}

!!

4

1 回答 1

2

Dapper 看到一个名为 的列Department,并试图将该值填充到一个称为的属性中Department,这意味着它正在尝试将一个int来自数据库的属性放入一个属性中:

public uDepartment Department { get; set; }

其中:效果不好。我可能会建议使对象与数据库匹配,例如:

public int Department { get; set; }

(可能还有public uDepartment DepartmentObject财产)

如果您希望域模型不这样做:那很好 - 但您可能需要一个不同的对象来与数据库对话,即您的域模型和您的数据库模型不需要是同一件事

于 2020-09-17T13:43:04.813 回答