我的项目的角色实体具有此建模的多重操作:
{
public string Uid { get; set; }
public string Descript { get; set; }
public bool Premitive { get; set; }
public virtual ICollection<ActionDto> Actions { get; set; }
public string Name { get; set; }
public bool IsDeleted { get; set; }
}
我使用UnitOfWork Repository Pattern create方法是:
public async Task<IHttpActionResult> Create([FromBody] RoleFullDto dto)
{
try
{
if (dto.Actions == null || dto.Actions.Count <= 0)
return BadRequest();
//If I Pass Only action uid, return EntityModelException
//When I Pass Complete Entity, Create New Action
//foreach (var action in dto.Actions)
//{
//var act = UnitOfWork.ActionRepository.Get(action.Uid);
//action.ActionName = act.ActionName;
//action.MenuId = act.MenuId;
//action.PersianActionName = act.PersianActionName;
//}
var role = ModelFactory.GetRole(dto);
if (role == null)
return Content(HttpStatusCode.InternalServerError, dto);
var result = await this.AppRoleManager.CreateAsync(role);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return ActionResult<Role>(role, null, "CreateRole", HttpStatusCode.Created);
}
catch (Exception e)
{
Console.WriteLine(e);
return InternalServerError();
}
}
我传递此参数以创建新角色:
{
Name: "TestRole1",
Descript: "This is Test",
Premitive: false,
Actions: [{uid:1},{uid:2},{uid:3}]
}
但是这个方法的魔杖添加了3个新的Action,它存在于Databese中 如何使用Exist操作创建角色?
答案 0 :(得分:0)
由于您传递的是不是来自数据库的实体,因此实体框架会尝试创建它们。您可以使用DBSet的Attach方法将操作对象链接到实体。但是既然你没有直接使用DBSet,你也可以这样做:
dto.Actions = dto.Actions.Select(a => UnitOfWork.ActionRepository.Get(a.Uid)).ToList();