2

I am developing a web application using AngularJS, ASP.NET, Entity Framework and a SQL Server database.

I want to insert some rows using EF with this method :

public string addRow(int CaptionID, string enLang)
{
    string output = "";
    try
    {
        var Cap = new Table_Name();

        string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

        Cap.CodeId = CaptionID;
        Cap.Created = DateTime.Now;
        Cap.CreatedBy = userName;
        Cap.ID = "";
        Cap.CodeLanguage = "en";
        Cap.CodeCountry = "GB";
        Cap.Caption = enLang;
        _db.Entry(Cap).State = EntityState.Added;

        _db.SaveChanges();

        output = "Created";

    }
    catch (Exception ex)
    {
        output = ex.InnerException.Message;
    }
    return output;
}

This function works.

But I have a question about the NEWID() function, I have searched a lot to know how to reproduce the same but I didn't knew, I've looked this thread but nothing.

In fact, I want to assign NEWID() to Cap.ID.

P.S : I know that is it possible to do it using SQLServer by assigning an SELECT NEWID() to Cap.ID, but I am looking for a way to do it using EF.

Community
  • 1
  • 1
ben
  • 398
  • 1
  • 6
  • 15

2 Answers2

4

Just do: Cap.ID = Guid.NewGuid();

Magnus
  • 45,362
  • 8
  • 80
  • 118
2

If you want that EF do the job for you you can do this in your Table_Name entity using Data Annotations:

public class Table_Name
{
  [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public Guid ID {get;set;}
  //...
}

This way you can define your ID column as Identity, and when you add new element and save changes, the database will generate the ID for you.

ocuenca
  • 38,548
  • 11
  • 89
  • 102