這是我的MVC模式:使用uniqueidentifier列類型和[DatabaseGenerated(DatabaseGeneratedOption.Identity)不EF代碼工作的首位
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
類:
public class LinkDBContext : DbContext
{
public DbSet<Link> Links { get; set; }
}
時,我想使用此代碼一些數據添加到數據庫:
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);
}
我只是得到一個例外是:Cannot insert the value NULL into column 'ID', table 'GhiasiDB.dbo.Links'; column does not allow nulls. INSERT fails.The statement has been terminated.
這是什麼問題,我該如何解決它?
更新
我改變的ID
類型從Guid
到int
,當我又試了一次,我得到這個例外,從List<Link> LLinks = Links.Links.ToList<Link>();
GetNewID
方法: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'.
,我不知道在哪裏做的來自。我將所有Guid
es更改爲int
!
ID列是uniqeidentifire,它的PK,但我仍然得到例外! –
@ahmadalishafiee您是否已將表中'ID'列的'Default Value或Binding'屬性設置爲'(newid())'? – Eranga
不,我沒有。但我已經做到了,它工作。謝謝。 –