如何处理实体框架5 code首先主键 [英] How to Handle Primary Key in Entity Framework 5 Code First

查看:197
本文介绍了如何处理实体框架5 code首先主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我EF5 code-首款车型,新纪录创造更好的工作,如果数据库设置主键。我使用的是GUID的主键,如果 DatabaseGeneratedOption.Identity 设置,SQL Server将始终创建唯一标识符

然而,这会导致问题,当我试图最初种子数据库。如果我在种方法中设置的GUID,SQL Server将重写它。如果我没有设置的GUID,每次都遇到了新的纪录。什么是推荐的解决方案使用pre-的GUID种子数据库,并保持 DatabaseGeneratedOption.Identity 我的正常操作设置?

例类模型:

  [重点]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)
公众的Guid标识{搞定;组; }
公共RecordName {搞定;组; }
公众的DateTime?创建{搞定;组; }
公众的DateTime?更新{搞定;组; }

例如种子的方法:

  VAR纪录=新记录()
            {
                ID =新的GUID(3B80725E-9550-4933-807F-C2FAA0942225),
                RecordName =新纪录,
                创建= DateTime.UtcNow,
                更新= DateTime.UtcNow,
             };
context.Record.AddOrUpdate(记录);
context.SaveChanges();


解决方案

AddOrUpdate有一个覆盖,它允许您指定密钥

MSDN

所以,你需要用自然键提供方法:

  context.Record.AddOrUpdate(C => c.RecordName,新记录()
            {
                RecordName =新纪录,
                创建= DateTime.UtcNow,
                更新= DateTime.UtcNow,
             })

In my EF5 code-first models, creation of new records works better if the database sets the primary key. I am using a Guid for primary key and if DatabaseGeneratedOption.Identity is set, SQL Server will always create the uniqueidentifier.

However, this causes issues when I am trying to initially seed the database. If I set the Guid in my seed method, SQL Server overrides it. If I don't set the Guid, I get a new record every time. What is a recommended solution to seed the database using pre-set Guids and keep DatabaseGeneratedOption.Identity set for my normal operations?

Example class model:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public RecordName { get; set; }
public DateTime? Created { get; set; }
public DateTime? Updated { get; set; }

Example seed method:

var record = new Record()
            {
                Id = new Guid("3B80725E-9550-4933-807F-C2FAA0942225"),
                RecordName = "New Record",
                Created = DateTime.UtcNow,
                Updated = DateTime.UtcNow,
             };
context.Record.AddOrUpdate(record);
context.SaveChanges();

解决方案

AddOrUpdate has an override that allows you to specify the key

From MSDN

So you need to supply the method with the natural key:

context.Record.AddOrUpdate(c => c.RecordName, new Record()
            {
                RecordName = "New Record",
                Created = DateTime.UtcNow,
                Updated = DateTime.UtcNow,
             })

这篇关于如何处理实体框架5 code首先主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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