1

我有类似的问题参考这个注释来解决他们的问题:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

但是,将其应用于我的相关实体模型什么也不做。

当我调用该.Add()方法时,它会将 GUID 插入为00000000-0000-0000-0000-000000000000.

如您所见,我提到的注释存在于模型中:

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

如何在插入新实体对象时生成唯一的 GUID?

4

1 回答 1

3

您始终可以在构造函数中初始化 Guid。

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; }
}
于 2013-08-01T20:37:01.670 回答