问题描述
在我的EF5代码优先模型中,如果数据库设置主键,创建新记录的效果会更好。我正在使用Guid的主键,如果设置了 DatabaseGeneratedOption.Identity
,SQL Server将始终创建 uniqueidentifier
。 但是,当我尝试初始种子数据库时,会导致问题。如果我在我的种子方法中设置Guid,SQL Server会覆盖它。如果我没有设定Guid,我每次都会获得新的记录。什么是建议的解决方案来种子数据库使用预设的Guid和保持 DatabaseGeneratedOption.Identity
设置为我的正常操作?
示例类模型:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id {get;组; }
public RecordName {get;组; }
public DateTime?创建{get;组; }
public DateTime?更新{get;组;
种子方法示例:
var record = new Record()
{
Id = new Guid(3B80725E-9550-4933-807F-C2FAA0942225),
RecordName =New记录,
Created = DateTime.UtcNow,
更新= DateTime.UtcNow,
};
context.Record.AddOrUpdate(record);
context.SaveChanges();
AddOrUpdate有一个覆盖,允许您指定密钥
从
所以你需要提供自然键的方法:
context.Record.AddOrUpdate(c => c.RecordName,new Record()
{
RecordName =New Record,
Created = 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代码首先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!