我在实体框架中存在关系问题
这是我的问题:
我有两个类:用户和组
User.cs:
public class User
{
[Key]
public int userId { get; set; }
[Display(Name="Firstname")]
public string firstname { get; set; }
[Display(Name = "Lastname")]
public string lastname { get; set; }
[Display(Name = "Email")]
public string email { get; set; }
}
Group.cs:
public class Group
{
[Key]
public int idGroup { get; set; }
public string name { get; set; }
public User owner { get; set; }
public List<User> members { get; set; }
public Group()
{
members = new List<User>();
}
}
这是插入组功能:
[HttpPost]
public ActionResult Create(Group group)
{
if (ModelState.IsValid)
{
group.owner = db.Users.Attach((User)Session["user"]);
//Current user stored in session and already presents in User table
db.Groups.Add(group);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View(group);
}
问题是:
任何帮助都会非常感激。
非常感谢
答案 0 :(得分:1)
试试这个:
public class Group
{
[Key]
public int idGroup { get; set; }
public string name { get; set; }
public virtual User owner { get; set; }
public virtual ICollection<User> members { get; set; }
public Group()
{
members = new List<User>();
}
}
答案 1 :(得分:0)
这可能会解决您的问题
Group group = db.Groups.Find(id).Include("owner");