Question

I've similar questions that refer to this annotation to solve their problem:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

However, applying this to my relevant Entity Model does nothing.

When I call the .Add() method, it inserts the GUID as 00000000-0000-0000-0000-000000000000.

As you can see, the annotation I mentioned is present in the model:

using System;
using System.Collections.Generic;

public partial class Event
{
    [System.ComponentModel.DataAnnotations.Schema.DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
    public System.Guid ID { get; set; }
    public int AccountID { get; set; }
    public string ExternalID { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Location { get; set; }
    public Nullable<System.DateTime> StartTime { get; set; }
    public Nullable<System.DateTime> EndTime { get; set; }
    public Nullable<bool> AllDay { get; set; }
    public Nullable<System.Guid> ImageData { get; set; }
    public string ImageUrl { get; set; }

    public virtual Account Account { get; set; }
    public virtual FetchedFile FetchedFile { get; set; }
}

How can I generate a unique GUID upon inserting a new Entity Object?

Was it helpful?

Solution

You can always initialize the Guid in a constructor.

public partial class Event
{
    public Event()
    {
        ID = Guid.NewGuid();
    }

    public System.Guid ID { get; set; }
    public int AccountID { get; set; }
    public string ExternalID { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Location { get; set; }
    public Nullable<System.DateTime> StartTime { get; set; }
    public Nullable<System.DateTime> EndTime { get; set; }
    public Nullable<bool> AllDay { get; set; }
    public Nullable<System.Guid> ImageData { get; set; }
    public string ImageUrl { get; set; }

    public virtual Account Account { get; set; }
    public virtual FetchedFile FetchedFile { get; set; }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top