这是我的模特:
public class Word
{
public string Word1 { get; set; }
public string SpecialCases { get; set; }
public virtual ICollection<Defination> Definations { get; set; }
}
public class Defination
{
public long WordId { get; set; }
public string Subjects { get; set; }
public virtual Word Word { get; set; }
public virtual ICollection<Example> Examples { get; set; }
}
public class Example
{
public long DefinationId { get; set; }
public string English { get; set; }
public virtual Defination Defination { get; set; }
}
我想用dapper将我的结果映射到模型。这是我使用它的代码,
string query =
$"SELECT Word.*, Defination.* " +
$"FROM Word Left Join Defination On Word.id = Defination.Id " +
$"WHERE Word.id = {id} ";
var item2 = cn.Query<Word, Defination, Word>(query,
(Word, Defination) =>
{
Word.Definations.Add(Defination);
Defination.Word = Word;
return Word;
}
);
return item2.FirstOrDefault();
我的问题是如何将示例数据添加到每个Defination模型。
答案 0 :(得分:0)
我从这段代码中解决了我的问题:
public Word GetByID(long id)
{
using (IDbConnection cn = Connection)
{
cn.Open();
const string wordQuery = "SELECT * FROM Word WHERE Id = @Id AND Word.SoftDelete = 0 ";
Word _word = cn.Query<Word>(wordQuery, new { Id = id }).FirstOrDefault();
if(_word != null && _word.Id != 0)
{
const string definationQuery = "SELECT * FROM Defination where WordId = @WordId AND SoftDelete = 0";
List<Defination> _defination = cn.Query<Defination>(definationQuery, new { WordId = _word.Id }).ToList();
_word.Definations = _defination;
if(_defination != null && _defination.Any())
{
const string exampleQuery = "SELECT * FROM Example where DefinationId = @DefinationId AND SoftDelete = 0";
for (int i=0; i<_defination.Count(); i++ )
{
_defination[i].Examples = cn.Query<Example>(exampleQuery, new { DefinationId = _defination[i].Id }).ToList();
}
}
}
return _word;
}
}
我知道它不够干净但它对我有用。感谢