我有类似的问题引用这个注释来解决他们的问题:
[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?
最佳答案
您始终可以在构造函数中初始化 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; }
}
关于database - 在 Entity Framework 5 中创建新对象时如何生成唯一的 GUID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18002632/