.net核心ef保存相关数据导致错误SqlException:无法在表中为identity列插入显式值

时间:2018-05-02 16:16:59

标签: asp.net-core-mvc asp.net-core-2.0 ef-core-2.0

关注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

0 个答案:

没有答案