有两种选择:
-
添加到
ICollection
让EF处理实体:
public virtual NewsDto InsertWithMedia(CreateNewsDto input, NewsAttachmentDto attach)
{
var news = ObjectMapper.Map<NewsManagement.News>(input);
news.Attachments = new List<NewsAttachment>(); // 1
var newsAttachment = ObjectMapper.Map<NewsAttachment>(attach);
news.Attachments.Add(newsAttachment); // 2
_newsRepository.Insert(news); // 3
CurrentUnitOfWork.SaveChanges(); // 4
return MapToEntityDto(news);
}
-
添加方式
Id
使用外键代替集合:
public class NewsAttachment: FullAuditedEntity<long>
{
// ...
public virtual long NewsId { get; set; }
public virtual News News { get; set; }
}
public virtual NewsDto InsertWithMedia(CreateNewsDto input, NewsAttachmentDto attach)
{
var news = ObjectMapper.Map<NewsManagement.News>(input);
var newsId = _newsRepository.InsertAndGetId(news); // 1
var newsAttachment = ObjectMapper.Map<NewsAttachment>(attach);
newsAttachment.NewsId = newsId; // 2
_newsAttachmentRepository.Insert(newsAttachment); // 3
CurrentUnitOfWork.SaveChanges(); // 4
return MapToEntityDto(news);
}
第二种方法适用于在以下情况下进行更新:
newsId
已经知道,但如果
NewsDto
也有
Attachments
(应该是
ICollection<AttachmentDto>
类型)。