我已经搜索过并尝试过针对我的问题的十几种解决方案,但是无法解决这个问题。
我在这里压缩了类定义,但这里是主要部分。
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
this.Device = new HashSet<Device>();
}
public virtual ICollection<Device> Devices { get; set; }
}
public class Device
{
public Device()
{
}
public int Id { get; set; }
public string DeviceId { get; set; }
public virtual ApplicationUser User { get; set; }
}
UserController.cs:
public async Task<ActionResult> SaveDevice(string id, string selection)
{
var selectedDevice = db.Devices.Where(u => u.DeviceId.Equals(selection));
var user = await UserManager.FindByIdAsync(id);
user.Devices.Add(selectedDevice.First());
==> here everything looks ok, device data can be seen from the user data
==> in comments different things that I have tried so far, without getting anything to work
//db.Entry(user).Property(p => p.Devices).IsModified = true;
//db.Entry(user).Reference(p => p.Devices).IsLoaded = true;
//db.Entry(user).Collection(p => p.Devices).IsLoaded = true;
//db.Entry(user).State = EntityState.Modified;
db.Users.Attach(user);
db.SaveChanges();
return RedirectToAction("Index");
}
==&GT;现在,当我返回用户详细信息视图时,设备数据为空,因此没有任何内容存储到db