0

C#, Entity Framework, MSSQL

Table is defined as the following:

id  uniqueidentifier (not null, PK, default (newid()) )
createdAt   datetimeoffset(3)   
updatedAt   datetimeoffset(3)   
version timestamp   
deleted bit 
Image   image   

I do have a many to one relationship assigned between the two tables. on tblArea.fkImages -> tblImages.id

If I insert a record by using this query the newid() appears to work and it assigns a random unique identifier.

insert into tblimages (image) values (null)

However, if I use the following C# code:

        Guid gRestID = Guid.Parse(tbxSelectedLoc.Text);

        tblImages newImage;

        tblArea newArea = new tblArea
        {
            Name = tbxAddMenu.Text,
            fkLoc = gRestID,
        };

        if (pbxLoc.Image != null)
        {
            newImage = new tblImages
            {
                Image = Helpers.ImageToByte(pbxLoc.Image),
            };
            db.tblImages.Add(newImage);
            newArea.tblImages = newImage;
        }


        db.tblArea.Add(newArea);
        db.SaveChanges();

Both record's ID's are 0's in tblArea and in tblImages which then prevents any subsequent additions to the two tables (constraints on the pk).

Anyone know why this is happening?

Zonus
  • 2,313
  • 2
  • 26
  • 48
  • Are you using code-first? You might want to look into the attribute `[DatabaseGenerated(...)]`? Or maybe it's related to http://stackoverflow.com/questions/23081096/entity-framework-6-guid-as-primary-key-cannot-insert-the-value-null-into-column – jjj Mar 10 '17 at 08:17
  • No, I'm not doing that.... It's all defined in the DB then pulled into my app. – Zonus Mar 10 '17 at 12:09

0 Answers0