C# MVC应用程序中未保存相关表
我有以下型号-C# MVC应用程序中未保存相关表,c#,entity-framework,asp.net-mvc-4,C#,Entity Framework,Asp.net Mvc 4,我有以下型号- public class RoleModel { public int Id { get; set; } public string RoleName { get; set; } public string Description { get; set; } public DateTime DateCreated { get; set; } public int CreatedBy { get; set; } public Date
public class RoleModel
{
public int Id { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
public DateTime DateCreated { get; set; }
public int CreatedBy { get; set; }
public DateTime LastUpdated { get; set; }
public int LastUpdateBy { get; set; }
[NotMapped]
public State State { get; set; }
public virtual IEnumerable<UserModel> Users { get; set; }
public virtual IEnumerable<UserModel> UsersNotInRole { get; set; }
public virtual int[] SelectedUsers { get; set; }
public virtual List<RightModel> Rights { get; set; }
public virtual List<RightModel> SelectedRights { get; set; }
public RoleModel()
{
}
}
public class RightModel
{
public string RightName { get; set; }
public string Description { get; set; }
public bool Assigned { get; set; }
}
以及我在RoleService中的更新方法-
public void Update(RoleModel entity)
{
entity.LastUpdated = DateTime.Now;
entity.LastUpdateBy = 1;
Role r = _roleRepository.FindById(entity.Id);
AutoMapper.Mapper.CreateMap<RoleModel, Role>();
_roleRepository.Update(AutoMapper.Mapper.Map(entity, r));
}
正如user3153169在评论中所说,对于集合,您需要为元素分配id/名称,使其类似于RoleModel.Rights[i],以便自动映射器查找元素 所以您应该使用for循环
@for (int i = 0 ; i < Model.Rights.Count() ; i++)
{
<tr>
<td>@Html.DisplayFor(model => Model.Rights[i].RightName)</td>
<td>@Html.DisplayFor(model => Model.Rights[i].Description)</td>
<td>
<div class="success-toggle-button">
@Html.CheckBoxFor(model => Model.Rights[i].Assigned, new { @class = "toggle" })
</div>
</td>
</tr>
}
for(int i=0;i请向我们展示您的角色服务的
更新(模型)
方法。我已经用这个inI更新了这个问题。我不确定这是否与您的问题有任何关系,但是说“避免调用构造函数内对象的虚拟成员”。EF使用虚拟属性作为“导航属性”并且将作为外键连接的结果延迟加载任何结果-您似乎没有在该类中使用列表,因此[I]将省略Users=new list()代码>现在是存储库的Update()
方法。如果您有更多的服务层:更新实际发生的方法。MVC编辑器无法处理foreach
编辑。改为尝试循环的
public void Update(RoleModel entity)
{
entity.LastUpdated = DateTime.Now;
entity.LastUpdateBy = 1;
Role r = _roleRepository.FindById(entity.Id);
AutoMapper.Mapper.CreateMap<RoleModel, Role>();
_roleRepository.Update(AutoMapper.Mapper.Map(entity, r));
}
public void Update(Role role)
{
_context.ObjectStateManager.ChangeObjectState(role, EntityState.Modified);
SaveChanges();
}
@for (int i = 0 ; i < Model.Rights.Count() ; i++)
{
<tr>
<td>@Html.DisplayFor(model => Model.Rights[i].RightName)</td>
<td>@Html.DisplayFor(model => Model.Rights[i].Description)</td>
<td>
<div class="success-toggle-button">
@Html.CheckBoxFor(model => Model.Rights[i].Assigned, new { @class = "toggle" })
</div>
</td>
</tr>
}