我正在尝试映射实体及其子集合。首先,我从数据库中检索实体和子集合:
declare @tbl table (id int, grpid char );
insert into @tbl
values (1,'a'), (2,'b'), (null,'b'), (3, 'a'), (null, 'c');
with cte as
( select id, grpid
from @tbl
where id is null
)
select grpid, id
from cte
union
select grpid, sum(id) as val
from @tbl
where not exists (select 1 from cte where cte.grpid = [@tbl].grpid)
group by grpid
order by grpid;
然后我使用mapper,但在这种情况下我丢失了EmailTemplateComponents中的EmailTemplate链接,我收到一个错误:
“$ id”:“1”, “消息”:“发生错误。”, “ExceptionMessage”:“操作失败:无法更改关系,因为一个或多个外键属性是 非空的。当对关系进行更改时,相关 foreign-key属性设置为空值。如果是外键的话 不支持null值,必须定义一个新的关系 必须为foreign-key属性分配另一个非null值,或者 必须删除不相关的对象。“, “ExceptionType”:“System.InvalidOperationException”,
我的实体是这样的:
public async Task<int> Update(EmailTemplateModel model, int id)
{
var emailTemplate = _context.EmailTemplates.Include("EmailTemplateComponents").Include("Site").FirstOrDefault(x => x.Id == id);
_mapper.Map(model, emailTemplate);
return await _context.SaveChangesAsync();
}
映射是这样的:
[Serializable]
public class EmailTemplate : EntityBase
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public string AuthorDisplayName { get; set; }
public int UserId { get; set; }
public bool IsDeleted { get; set; }
public virtual List<EmailTemplateComponent> EmailTemplateComponents { get; set; }
//Site
public int SiteId { get; set; }
[ForeignKey("SiteId")]
public virtual Site Site { get; set; }
}
[Serializable]
public class EmailTemplateComponent : EntityBase
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public bool IsTop { get; set; }
public bool IsBottom { get; set; }
public bool AlignRight { get; set; }
public string Text { get; set; }
public string Title { get; set; }
public string Url { get; set; }
public string ImageUrl { get; set; }
//Email template
public int EmailTemplateId { get; set; }
[ForeignKey("EmailTemplateId")]
public virtual EmailTemplate EmailTemplate { get; set; }
}
我似乎无法弄清楚为什么用null替换子集合中的值?