我正在使用Automapper映射我的实体对象,正如您将在下面的评论中看到的那样,我的集合在映射后会丢失。
public partial class WebUser
{
public WebUser()
{
this.WebUserGroups = new HashSet<WebUserGroup>();
}
public int UserKey { get; set; }
//stuff
public virtual ICollection<WebUserGroup> WebUserGroups { get; set; }
}
public void Edit(WebUser user)
{
//Has collection of WebUserGroups populated
var userToBeEdited = GetUserBy(user.UserKey);
var updatedWebUser = Mapper.Map(user, userToBeEdited);
//Lost after mapping
_context.Entry(updatedWebUser).State = EntityState.Modified;
_context.SaveChanges();
}
public WebUser GetUserBy(int userKey)
{
return (from webUser in _context.WebUsers
join webUserGroup in _context.WebUserGroups on webUser.UserKey equals webUserGroup.UserKey
select webUser).FirstOrDefault();
}
Mapper.CreateMap<WebUser, WebUser>()
.ForSourceMember(dest => dest.UserKey, src => src.Ignore())
.ForSourceMember(dest => dest.WebUserGroups, src => src.Ignore());
任何建议?
答案 0 :(得分:1)
我认为您需要.ForMember
而不是.ForSourceMember
:
Mapper.CreateMap<WebUser, WebUser>()
.ForMember(dest => dest.UserKey, opt => opt.Ignore())
.ForMember(dest => dest.WebUserGroups, opt => opt.Ignore());