代码首先是CTP4和主键 [英] Code first CTP4 and primary key
问题描述
Hello
我正在尝试代码第一种方法使用EF。
我有一个这样的Person类:
公共类人员
{
公共Guid ID {get; set;}
公共字符串名称{get; set;}
}
在OnModelCreating中我写了这个
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
modelBuilder.IncludeMetadataInDatabase = false;
modelBuilder.Entity<人>()HasKey(人=> person.ID);
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; base.OnModelCreating(modelBuilder);
}
但如果我写:
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; Models.Person P = new Person();
P.ID = Guid.NewGuid();
P.Name =" Jhon"; $
P.Surname =" Smith";&
DB.Persons.Add(P);
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; Models.Person P1 =新Models.Person();
的&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP ;&NBSP; P1.ID = P.ID; //上一个实体的相同ID <
  ; P1.Name = QUOT; JHON英寸;
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; P1.Surname = QUOT;史密斯英寸;
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; DB.Persons.Add(P1);
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; DB.SaveChanges();
当DB.SaveChanges()提升时,DB.Persons.Add(P1)不会产生错误来自数据库的主键冲突错误。
此行为是否正确?
上下文无法检测到DB.Persons.Add(P1)处的冲突?
非常感谢和最好的问候
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; DB.SaveChanges();
是的,这是正确的行为,EF认为所有添加的对象都有"临时密钥"。他们被允许冲突,直到它成为拯救的时候。这是为了方便商店生成的密钥以及在保存之前分配密钥
的自定义逻辑。
希望这有帮助。
〜罗文
Hello
I am trying the code first approach with EF.
I have a Person class like this :
public class Person
{
public Guid ID {get;set;}
public string Name {get;set;}
}
In the OnModelCreating I wrote this
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
modelBuilder.IncludeMetadataInDatabase = false;
modelBuilder.Entity<Person>().HasKey(person => person.ID);
base.OnModelCreating(modelBuilder);
}
but if I write :
Models.Person P = new Person();
P.ID = Guid.NewGuid();
P.Name = "Jhon";
P.Surname = "Smith";
DB.Persons.Add(P);
Models.Person P1 = new Models.Person();
P1.ID = P.ID; // the same ID of the previous istance
P1.Name = "Jhon";
P1.Surname = "Smith";
DB.Persons.Add(P1);
DB.SaveChanges();
DB.Persons.Add(P1) does not generate errors while DB.SaveChanges() raise the primary key violation error coming from database.
is this behavior correct ?
the context could not detect the conflict at DB.Persons.Add(P1) ?
Many Thanks and best regards
DB.SaveChanges();
Hi,
Yes that is the correct behavior, EF considers all added objects to have "temporary keys" and they are allowed to conflict until it becomes time to save. This is designed to facilitate store generated keys and also custom logic that will assign keys just before saving.
Hope this helps.
~Rowan
这篇关于代码首先是CTP4和主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!