所以我正在用我的解决方案制作的ASP.NET身份模板构建我的项目。我有以下模型组成我的数据库但是当我尝试创建一个新的会话时,它没有被分配一个ID。
public class Client
{
public Client()
{
Session = new HashSet<Session>();
}
[Key, ForeignKey("ApplicationUser")]
public string Id { get; set; }
public virtual ICollection<Session> Session { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
public class Session
{
public string Id { get; set; }
public virtual Client Client { get; set; }
public virtual Measurements Meansurements { get; set; }
public virtual MeasurementsExtended MeasurementsExtended { get; set; }
}
public class Measurements
{
[Key, ForeignKey("Session")]
public string Id { get; set; }
public virtual Session Session { get; set; }
}
public class MeasurementsExtended
{
[Key, ForeignKey("Session")]
public string Id { get; set; }
public virtual Session Session { get; set; }
}
更新控制器
var session = new Session { Client = db.Client.Find(model.SelectedClient),};
var measurements = new Measurements { Session = session};
var measurementsExtended = new MeasurementsExtended { Session = session};
ession.Meansurements = measurements;
session.MeasurementsExtended = measurementsExtended;
db.Session.Add(session);
我是否明确需要分配ID?对于任何其他自定义模型,我没有这样做,并且它们被分配了ID而没有问题 我仍然是MVC的新手,如果有其他我可能做错的话,我可以随时告诉我
更新
所以在讨论之后我已经修复了数据库生成ID,但现在我得到错误InnerException {"Cannot insert the value NULL into column 'Id', table 'project.dbo.Sessions'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}
然而,当我在调试器中查看对象时,它确定Id为0,我甚至尝试将其手动设置为1而没有任何变化。
更新2 - 工作
模型
public class Session
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid Id { get; set; }
...
控制器
var session = new Session { Id = Guid.NewGuid() ...