使用UniqueIdentifier列类型和[DatabaseGenerated(DatabaseGeneratedOption.Identity)]对于模型的键在EF代码中不起作用 [英] Use UniqueIdentifier column type and [DatabaseGenerated(DatabaseGeneratedOption.Identity)] for model's key doesn't work in EF Code First
问题描述
这是我的MVC模型:
public class Link
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ID { get; set; }
[DisplayName("Shorted URL")]
public string SURL { get; set; }
[DisplayName("General Link")]
public string OriginalURL { get; set; }
[DisplayName("Click Count")]
public int ClickCount { get; set; }
}
这是 LinkDBContext
class:
public class LinkDBContext : DbContext
{
public DbSet<Link> Links { get; set; }
}
when I want to add some data to database using this code:
private string GetNewID(string url, string id)
{
LinkDBContext Links = new LinkDBContext();
//id = "http://" + id;
List<Link> link = Links.Links.Where(a => (a.OriginalURL == id && a.SURL == id)).ToList();
if (link.Count == 0)
{
List<Link> LLinks = Links.Links.ToList<Link>();
Link li = new Link();
//li.ID = new Guid();
li.ClickCount = 0;
li.SURL = id;
li.OriginalURL = url;
Links.Links.Add(li);
Links.SaveChanges();
Links.Dispose();
return id.ToString();
}
return GetNewID(url);
}
我只得到一个异常:将值NULL转换为列'ID',表'GhiasiDB.dbo.Links';列不允许空值。 INSERT fails.The语句已终止。
I just get an exception that is: Cannot insert the value NULL into column 'ID', table 'GhiasiDB.dbo.Links'; column does not allow nulls. INSERT fails.The statement has been terminated.
问题是什么,如何解决?
what is the problem and how can I resolve it?
更新
我更改了 ID
从 Guid
到 int
列表< Link> LLinks = Links.Links.ToList< Link>();
GetNewID
方法:链接无法设置为Guid值。您必须将此属性设置为类型Int32的非空值。
,我不知道它来自哪里。我将所有 Guid es改为
int
!
I changed the type of ID
from Guid
to int
and when I tried again I got this exception from List<Link> LLinks = Links.Links.ToList<Link>();
of GetNewID
method:The 'ID' property on 'Link' could not be set to a 'Guid' value. You must set this property to a non-null value of type 'Int32'.
and I don't know where did it come from. I changed all Guid
es to int
!
推荐答案
如果允许EF生成表,它将创建一个默认值设置为(newid())
的PK。如果您先设计数据库,可以手动设置。
If you allowed EF to generate the tables it would create the PK with a default value set to (newid())
. You can set it manually if you designed the database first.
这篇关于使用UniqueIdentifier列类型和[DatabaseGenerated(DatabaseGeneratedOption.Identity)]对于模型的键在EF代码中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!