我首先尝试将 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/