1

I'm using Asp.net mvc 5 and EF 6 to make a web app. I started with the Internet app template and added those classes:

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

But every time the nuget package manager updates the db and runs the Seed method, it breaks when trying to insert an article in the db. here's the seed method in the configuration.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

The inner exception: System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'ID', table 'aspnet-Webapp-20141022011020.dbo.Articles'; column does not allow nulls. INSERT fails I get the same error if I take the [Key] adnotation out of the Article class and if I take the [DatabaseGenerated(DatabaseGeneratedOption.Identity)] adnotation I get the following error: System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK_dbo.Articles'. Cannot insert duplicate key in object 'dbo.Articles'. The duplicate key value is (00000000-0000-0000-0000-000000000000).

With long/int in Guid's place I get an update-database error like: uniqueidentifier is incompatible with bigint/int.

What can I do? Why isn't it generating a proper id with guid?

Sahan Serasinghe
  • 1,591
  • 20
  • 33
Cristian Dan
  • 173
  • 3
  • 14

1 Answers1

3

You have to tell the database that you want such behavior. Usually the EF6 is smart enough if you use code-first approach, it'll be able to generate the correct behavior.

Go to the database, modify the ID field, and add this to default value: newsequentialid().

If you want to create the Guid yourself:

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

}
Erti-Chris Eelmaa
  • 25,338
  • 6
  • 61
  • 78
  • sorry ... I add newsequentialid() where? – Cristian Dan Dec 28 '14 at 21:47
  • @CristianDan; you can try running this SQL query on your database: `ALTER TABLE dbo.TableName ADD CONSTRAINT DF_ColumnName DEFAULT newsequentialid() FOR ColumnName`, replace the names with your table/ID column. – Erti-Chris Eelmaa Dec 28 '14 at 21:53
  • 1
    thanks very much .. it's working ... I found out where to write newsequentialid() :D thanks – Cristian Dan Dec 28 '14 at 21:57
  • Just one last question ... is there any annotation for EF to know to use newsequentialid() for default? or it's something you have to manually specify in the db? – Cristian Dan Dec 28 '14 at 22:09
  • @CristianDan: if you use database-first approach, then you have to do it manually (which you do, I think). If you use Code-first approach(eg database is generated from the model), it'll be done automatically. – Erti-Chris Eelmaa Dec 28 '14 at 22:17
  • I use code first, that's the reason I used those two annotation [Key] and [DatabaseGenerated(DatabaseGeneratedOption.Identity)] to tell EF how I want the db to be built. – Cristian Dan Dec 28 '14 at 22:19
  • Just wanted to point out that if you don't want sequential, you can just use `NEWID()` – zaitsman Dec 28 '14 at 22:41
  • 1
    @CristianDan: you might need to modify the code-first migration file, those attributes are not enough: http://stackoverflow.com/questions/18200817/how-to-set-newid-for-guid-in-entity-framework see answer by Joy. – Erti-Chris Eelmaa Dec 28 '14 at 23:06
  • 1
    +1. Thanks for the answer but I think `Guid = Guid.NewGuid();` should be `ID = Guid.NewGuid();` Unless I'm missing something here? – Nico Apr 02 '15 at 19:02
  • I'm setting the ID myself but EF is overriding it. – David Sopko Feb 26 '19 at 19:34