c# - 使用 Entity Framework 手动输入 key

标签 c# sql asp.net entity-framework entity-framework-core

我首先尝试将 Entity Framework 代码用于一个简单的数据库项目,但我遇到了一个我根本无法弄清楚的问题。

我注意到 EF 将我的表的 ID 设置为每次自动增加 1,完全忽略了我为该字段手动输入的值。经过一番搜索后,我了解到禁用此行为的正确方法是:

modelBuilder.Entity<Event>().Property(e => e.EventID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

但是现在我只是收到这个错误,我不知道为什么:

Unhandled Exception: System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---

System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Cannot insert explicit value for identity column in table 'Events' when IDENTITY_INSERT is set to OFF.

如果有帮助,这里是有问题的 POCO 类:

public class Event
{
    [Key, Required]
    public int EventID { get; set; }

    public string EventType { get; set; } //TODO: Event Type Table later on
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }

    public virtual ICollection<Match> Matches { get; set; }
    public virtual ICollection<EventParticipation> EventParticipation { get; set; }
}

提前致谢。

最佳答案

因为我更喜欢属性,为了完整起见,这里有一个替代方案:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }

注意:这也适用于 EF Core。

关于c# - 使用 Entity Framework 手动输入 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18907411/

相关文章:

sql - Oracle SQL 比较包含数字的字符串,从 0(零)开始

java - 消息: ORA-04079: invalid trigger specification in eclipse

c# - 集群队列的 IBM MQ 问题

c# - 在 ASP.NET MVC 3 中,如何使用 LINQ 只检索我想要的实体对象?

php - SQL 更新 : Append data to a cell

asp.net - 从输出缓存中排除动态渲染的用户控制

javascript - 如何避免页面刷新时调用js函数

asp.net - 在 LINQ-to-SQL 中运行映射存储过程方法时生成奇怪的 system.void 返回异常

c# - 对象引用行为

c# - 找不到类型或命名空间(但应该是!)