实体框架 6 Guid 生成 null
本文关键字:生成 null Guid 框架 实体 | 更新日期: 2023-09-27 18:35:34
我正在使用 Asp.net mvc 5和EF 6来制作Web应用程序。我从互联网应用程序模板开始并添加了这些类:
public class Article
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ID { get; set; }
public string Tags { get; set; }
public string Name { get; set; }
public string Link { get; set; }
public string HtmlContent { get; set; }
[ForeignKey("ListaId")]
public Lista Lista { get; set; }
public Guid ListaId { get; set; }
}
public class List
{
public string Name { get; set; }
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ID { get; set; }
public int Status { get; set; }
public virtual ApplicationUser User { get; set; }
public string ApplicationUserId { get; set; }
public string Tags { get; set; }
}
但是,每次 nuget 包管理器更新数据库并运行 Seed 方法时,它都会在尝试在数据库中插入文章时中断。下面是配置中的种子方法.cs
context.Lists.AddOrUpdate(new Lista
{
Name = "Technology",
ApplicationUserId = "f06b0d2e-2088-4cd7-8b1c-4fcad5619f3c",
Status = 1,
Tags = "Tech,News"
});
context.SaveChanges();
Lista l1 = context.Lists.Where(x => x.Status == 1).First();
context.Articles.AddOrUpdate(new Article
{
ListaId = l1.ID,
Link = "www.abc.com",
Name = "ABC",
Tags = "c,test",
HtmlContent = "Hello World"
});
context.SaveChanges(); //here it breaks
内部异常:System.Data.SqlClient.SqlException:无法插入 值 NULL 到列"ID"中,表 'aspnet-Webapp-20141022011020.dbo.Articles';列不允许 空值。插入失败,如果我使用 [密钥] ,我会收到同样的错误 注释出文章类,如果我采取 [DatabaseGenerated (DatabaseGenerated Option.Identity)] 我得到的注释 以下错误:System.Data.SqlClient.SqlException:违反 主键约束 'PK_dbo。文章'。无法插入重复的键 在对象'dbo。文章'。重复的键值为 (
00000000-0000-0000-0000-000000000000)。
在 Guid 的位置使用 long/int,我得到一个更新数据库错误,例如:uniqueidentifier 与 bigint/int 不兼容。
我能做什么?为什么它没有使用 guid 生成正确的 id?
你必须告诉数据库你想要这样的行为。通常,如果使用代码优先方法,EF6 就足够智能,它将能够生成正确的行为。
转到数据库,修改ID
字段,并将其添加到默认值:newsequentialid()
。
如果要自己创建 Guid:
public class Article
{
[Key]
public Guid ID { get; set; }
public string Tags { get; set; }
public string Name { get; set; }
public string Link { get; set; }
public string HtmlContent { get; set; }
[ForeignKey("ListaId")]
public Lista Lista { get; set; }
public Guid ListaId { get; set; }
public Article(){
ID = Guid.NewGuid();
}
}