我需要在OptionRoleTable:
public class OptionRole
{
public int Id { get; set; }
public int RoleId { get; set; }
public int OptionsId { get; set; }
public virtual Role Role { get; set; }
public virtual Options Options { get; set; }
}
这是Options Tabel
:
public partial class Options
{
public int Id { get; set; }
public string OptionName { get; set; }
public string RouteFunctionName { get; set; }
public string Icon { get; set; }
public virtual ICollection<OptionRole> OptionRoles { get; set; }
}
当我使用此代码在OptionRole
中添加数据时,我必须检查OptionRole
中不存在的数据:
public async Task<Options> findOptionsId(int optionId)
{
return await _option.FirstOrDefaultAsync(x => x.Id == optionId);
}
public async Task<bool> AddorUpdateOptions(int optionId, IList<int> selectedRoleValue)
{
List<OptionVM> optionVMs = new List<OptionVM>();
List<int> currentOptionValue = new List<int>();
var optionRole = await findOptionsId(optionId);
if (optionRole == null)
{
return false;
}
foreach (var item in selectedRoleValue)
{
var findRole = await _roleManager.FindByIdAsync(item);
var findOPR = optionRole.OptionRoles.FirstOrDefault(x => x.OptionsId== optionId && x.RoleId==item);
if (findOPR != null)
{
currentOptionValue.Add(item);
}
}
if (selectedRoleValue == null)
{
selectedRoleValue = new List<int>();
}
var newOptionRole = selectedRoleValue.Except(currentOptionValue).ToList();
foreach (var opRole in newOptionRole)
{
var findRole = await _roleManager.FindByIdAsync(opRole);
if (findRole != null)
{
optionRole.OptionRoles.Add(new OptionRole
{
OptionsId = optionRole.Id,
RoleId = findRole.Id
});
}
}
var removeOptionRole = currentOptionValue.Except(selectedRoleValue).ToList();
foreach (var remove in removeOptionRole)
{
var findOptionRole = _optionRoles.FirstOrDefault(x => x.Id == remove);
if (findOptionRole != null)
{
optionRole.OptionRoles.Remove(findOptionRole);
}
}
return Update(optionRole.OptionRoles);
}
使用此代码时,我必须通过Options
类类型。它向我显示此错误:
严重性代码描述项目文件行抑制状态 错误CS1503参数1:无法从“ System.Collections.Generic.ICollection”转换为“ StoreFinal.Entities.Entities.Identity.OptionRole” StoreFinal.Services C:\ Users \ Mr-Programer \ Desktop \ New folder \ StoreFinal \ StoreFinal。 Services \ Contracts \ Identity \ Service \ ApplicationOptionRoleManager.cs 97有效
此行错误:return Update(optionRole.OptionRoles);
出什么问题了?我该如何解决这个问题?
编辑:
更新方法:
public virtual bool Update(T entity)
{
try
{
Entities.Attach(entity);
return true;
}
catch (Exception)
{
return false;
}
}
答案 0 :(得分:1)
查看“更新方法”签名:
public virtual bool Update(T entity);
它接受参数类型T,它应该是一个实体-为什么选择一个实体-因为Entities.Attach()仅接受1个对象。当您传递给它的时候:
return Update(optionRole.OptionRoles);
其中OptionRoles类型为:ICollection
为便于理解,请将其更改为
return Update(optionRole.OptionRoles[0]);
或
return Update(optionRole.OptionRoles.First());
然后共享结果。