database - 在 Entity Framework 5 中创建新对象时如何生成唯一的 GUID?

标签 database asp.net-mvc-4 entity-framework-5 guid identity

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

[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/

相关文章:

c# - 如何解决 EF 5 Code First 中组合的一对一和一对多关系

sql - 比较 SQL Server 数据库和自动映射

c# - 由于 Web API 中的特殊字符,未设置发布值

sql-server-2008-r2 - Entity Framework 代码第一基类未映射到数据库

c# - Web API 中的单元测试自定义路由

c# - 从 ASP.Net MVC 4 中的 Kendo UI MultiSelect 获取 PrimaryId

c# - 从 Entity Framework 中的表值函数创建集合

php - 如何在php中的所有行中回显列的所有名称

database - Heroku billing dynos 是如何工作的?

android - 需要算法 SQLite Android