与实体框架手动输入键 [英] Entering keys manually with Entity Framework

查看:149
本文介绍了与实体框架手动输入键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想先用实体框架code为一个简单的数据库项目,我碰到一个问题,我根本无法弄清楚。

我注意到EF被设定ID为我的表,每次1自动增加,完全无视我手动输入该字段的值。经过一番搜索这是我的理解是禁止这种行为的正确方法是这样做的:

  modelBuilder.Entity<事件>()房产(E => e.EventID)。.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

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


  

未处理的异常:
  System.Data.Entity.Infrastructure.DbUpdateException:错误
  在更新的条目出现。请参阅内部异常
  详细信息。 ---


  
  

    

System.Data.UpdateException:更新条目时发生错误。详情请参阅内部异常。 --->
    System.Data.SqlClient.SqlException:无法插入显式值
    标识列在表'事件'当IDENTITY_INSERT设置为OFF。


  

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

 公共类事件
{
    [关键,必需]
    公众诠释事件ID {搞定;组; }    公共字符串事件类型{搞定;组; } // TODO:事件类型表以后
    公开日期时间起始日期{搞定;组; }
    公共DateTime的结束日期{搞定;组; }    公共虚拟的ICollection<匹配和GT;匹配{搞定;组; }
    公共虚拟的ICollection< EventParticipation> EventParticipation {搞定;组; }
}

先谢谢了。


解决方案

默认情况下实体框架假定是数据库生成一个整数的主键(相当于添加属性 HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)或致电属性(E => e.EventID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); 在流利的API

如果你看一下,创建你应该可以看到这个表中的迁移:

  CREATETABLE(
                dbo.Events
                C =>新
                    {
                        事件ID = c.Int(可空:假的,身份:真)
                        //等等
                    })
                .PrimaryKey(T => t.EventID);

然后你改变使用流利的API来 DatabaseGenerated.None 模型。 EF把这个在迁移:

  AlterColumn(dbo.Events,事件ID,C = GT; c.Int(可空:假的,身份:FALSE))

和生成的SQL是这样的:

ALTER TABLE [DBO]。[活动] ALTER COLUMN [事件ID] [INT] NOT NULL

这实际上做diddly蹲下。 <一href=\"http://stackoverflow.com/questions/8230257/sql-server-remove-identity-from-a-column-in-a-table\">Dropping中某列的IDENTITY 是不平凡的。您需要删除并重新创建表或创建新列,那么你必须复制数据,并修复了外键。因此,这并不奇怪,EF是不是做了你。

您需要解决如何最好地做自己。你可以从头开始,现在回滚迁移至0并重新脚手架已指定 DatabaseGeneratedOption.None ,或者你可以手动更改迁移删除并重新创建该表。

或者你也可以删除并重新列:

  DropColumn(客户,客户ID);
AddColumn(客户,客户ID,C = GT; c.Long(可空:假的,身份:FALSE));

修改
或者你可以<一个href=\"http://romiller.com/2013/04/30/ef6-switching-identity-onoff-with-a-custom-migration-operation/\"相对=nofollow>切换标识开/关与自定义迁移操作

I'm trying to use Entity Framework code first for a simple database project and I run into a problem I simply cannot figure out.

I noticed EF was setting the ID for my tables automatically increasing by 1 each time, completely ignoring the value I entered manually for that field. After some searching it is my understanding that the right way to disable this behavior is doing:

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

However now I'm just getting this error and I have no idea why:

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.

If it's helpful, here is the POCO class in question:

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

Thanks in advance.

解决方案

By default Entity Framework assumes that an integer primary key is database generated (equivalent to adding the attribute HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity) or calling Property(e => e.EventID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); in the Fluent API.

If you look at the migration that creates the table you should see this:

   CreateTable(
                "dbo.Events",
                c => new
                    {
                        EventID = c.Int(nullable: false, identity: true),
                        //etc
                    })
                .PrimaryKey(t => t.EventID );

Then you changed the model using the Fluent API to DatabaseGenerated.None. EF puts this in the migration:

AlterColumn("dbo.Events", "EventID", c => c.Int(nullable: false, identity: false))

And the sql generated is this:

ALTER TABLE [dbo].[Events] ALTER COLUMN [EventID] [int] NOT NULL

Which actually does diddly squat. Dropping the IDENTITY from a column is not trivial. You need to drop and recreate the table or create a new column, then you have to copy the data and fix up foreign keys. So it's not surprising that EF isn't doing that for you.

You need to work out how best to do it for yourself. You could roll back your migrations to 0 and re-scaffold from scratch now that you have specified DatabaseGeneratedOption.None, or you could change the migration manually to drop and recreate the table.

Or you could drop and recreate the column:

DropColumn("Customer", "CustomerId"); 
AddColumn("Customer", "CustomerId", c => c.Long(nullable: false, identity: false));

EDIT Or you could Switch Identity On/Off With A Custom Migration Operation

这篇关于与实体框架手动输入键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆