Asp.net mvc 更新EF ICollection属性
如何更新EF中的ICollection属性 我得到这个错误信息 无法将类型“int”隐式转换为“Asp.net mvc 更新EF ICollection属性,asp.net-mvc,entity-framework,one-to-many,Asp.net Mvc,Entity Framework,One To Many,如何更新EF中的ICollection属性 我得到这个错误信息 无法将类型“int”隐式转换为“System.Collections.Generic.ICollection” 我的实体: public class Department { public virtual int Id { get; set; } public virtual string DepartmentTitle { get; set; } public virtual ICollection<
System.Collections.Generic.ICollection
”
我的实体:
public class Department
{
public virtual int Id { get; set; }
public virtual string DepartmentTitle { get; set; }
public virtual ICollection<UserProfile> UserProfiles { get; set; }
}
public class UserProfile
{
public virtual int UserId { get; set; }
public virtual string UserName { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
}
department.UserId=uProfile.UserId代码>所以。。。部门中的UserId属性在哪里?我想您需要Department.UserProfiles.Add(文件)代码>但从您的示例中很难判断您的意图是什么。我写了一篇关于如何使用导航属性的教程,你可能会觉得很有帮助:这是一篇关于导航属性如何工作以及如何使用导航属性的概述哦,对不起!应该是“department.UserProfiles”,而不是“department.UserId”。我现在已经更正了上面的代码。当然,这是在这里,它的工作不好。UserProfiles属性是ICollection,我的问题是如何向这样的属性添加新值。实际上是UserProfiles表中的外键。通常是一个非常简单的动作,但我该怎么做呢?哦,我再次感到抱歉。我错过了你的参赛作品卢克·麦格雷戈。谢谢我得到了它。结果很完美!这很奇怪。您的指南以更新数据的方式运行,但仍会抛出错误消息:“保存不公开其关系的外键属性的实体时出错。EntityEntries属性将返回null,因为无法将单个实体标识为异常源。通过在实体类型中公开外键属性,可以更轻松地在保存时处理异常。有关详细信息,请参见InnerException“
var userProfile = _db.UserProfiles.Single(d => d.UserName == "SomeUserName");
var department = _db.Departments.Single(d => d.Id == variableDepartmentID);
department.UserProfiles = uProfile.UserId;
_db.UpdateDepartment(department);
_db.Save();