关注this guide,我尝试在我的网络应用中执行相同操作:
var content = new Content()
{
IsActive = true,
Link = new Link()
{
DateCreated = DateTime.UtcNow,
LinkName = model.Name,
LinkDesc = model.Description,
LinkPath = model.LinkPath,
IsActive = true
}
};
_context.Contents.Add(content);
_context.SaveChanges();
这会引发错误:
SqlException:无法在标识列中插入显式值 表'链接'当IDENTITY_INSERT设置为OFF时。
但如果我这样做,它就有效:
var content = new Content() {
IsActive = true
}
_context.Contents.Add(content);
_context.SaveChanges();
var link = new Link()
{
DateCreated = DateTime.UtcNow,
LinkName = model.Name,
LinkDesc = model.Description,
LinkPath = model.LinkPath,
IsActive = true,
ContentId = content.ContentId
};
_context.Links.Add(link);
_context.SaveChanges();
content.LinkId = link.LinkId;
_context.SaveChanges();
这些是模型:
public class Content
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ContentId { get; set; }
public int? LinkId { get; set; } = null;
[ForeignKey("LinkId")]
public virtual Link Link { get; set; }
public DateTime DateCreated { get; set; } = DateTime.UtcNow;
public bool IsActive { get; set; }
}
public class Link
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int LinkId { get; set; }
[MaxLength(300)]
public string LinkDesc { get; set; }
[MaxLength(50)]
[Required]
public string LinkName { get; set; }
public DateTime DateCreated { get; set; } = DateTime.UtcNow;
public bool IsActive { get; set; }
[MaxLength(500)]
public string LinkPath { get; set; }
public int ContentId { get; set; }
[ForeignKey("ContentId")]
public virtual Content Content { get; set; }
}
我错过了什么吗?为什么第一个代码会尝试将值插入LinkId
?