Use UniqueIdentifier column type and [DatabaseGene

2020-06-28 07:10发布

This is my MVC model:

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; }
}

and this is 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);
    }

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?


update

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 Guides to int!

4条回答
干净又极端
2楼-- · 2020-06-28 07:15

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.

查看更多
趁早两清
3楼-- · 2020-06-28 07:25

I think that's because Guid and Identity are not compatible. How do you think to auto-increment Guid?

Maybe changing Id to int could help you

查看更多
可以哭但决不认输i
4楼-- · 2020-06-28 07:26

If the table already existed before adding [DatabaseGenerated(DatabaseGeneratedOption.Identity)], then remove the DbSet, run Update-Database, add the DbSet again, finally run another Update-Database.

At least that's what fixed it for me.

查看更多
爷的心禁止访问
5楼-- · 2020-06-28 07:32

Guid is structure type i.e value type. You can not assign null to value type. If you want this than in that case you can use "?" after type in declaration.

  public Guid? ID { get; set; }

if this still does not help, try an int

查看更多
登录 后发表回答