简体   繁体   English

实体框架,POCO和私有财产

[英]Entity framework, POCO and a private property

I've created the following POCO class and also made Contact.FirstName and Contact.LastName properties private ( these properties are mapped to appropriate properties in an Entity Framework model ). 我创建了以下POCO类,并将Contact.FirstNameContact.LastName属性设为私有(这些属性映射到Entity Framework模型中的相应属性)。

public class Contact
{
    public int ContactID { get; set; }
    private string FirstName { get; set; }
    public string LastName { get; private set; }
}

I expected to get an exception due to EF not being able to assign values to these two properties, but somehow EF still managed to assign values to them. 我期望得到一个例外,因为EF无法为这两个属性赋值,但不知何故EF仍设法为它们赋值。 How is that possible, since only code in Contact class should have accesses to private properties? 这怎么可能,因为只有Contact类中的代码才能访问私有属性?

Thank you 谢谢

在具有足够信任级别的环境中,可以使用反射来访问通常无法访问的成员。

For completeness' sake: EF5 code first doesn't (at least by default) map private properties to a database table column. 为了完整起见:EF5代码首先不(至少默认情况下)将私有属性映射到数据库表列。

The following class: 以下课程:

public class Person {
  public int PersonId { get; set; }
  private string Name { get; set; }
}

With the following DbContext: 使用以下DbContext:

public class PrivatePropertiesContext : DbContext {
  public DbSet<Person> People {
    get;
    set;
  }
}

Generates a People table with only one column: dbo.People.PersonId (PK, int, not null) 生成只有一列的People表: dbo.People.PersonId (PK, int, not null)

A public key property is required by default code first conventions. 默认代码优先约定需要公钥属性。 If the PersonId property in the Person class would be private or protected, entity framework throws the following exception: 如果Person类中的PersonId属性是私有的或受保护的,则实体框架会抛出以下异常:

System.Data.Entity.Edm.EdmEntityType: : EntityType 'Person' has no key defined. Define the key for this EntityType.
System.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'People' is based on type 'Person' that has no keys defined.

Yes - EF, code first are utilizing that in couple places. 是的 - EF,代码首先在几个地方使用它。

I've seen similar behavior with private constructors - EF/CF can still construct your objects even if you 'hide' it, or try to :) (that was the behavior in earlier versions, not sure now). 我已经看到了私有构造函数的类似行为 - 即使你'隐藏'它,或者尝试:),EF / CF仍然可以构造你的对象(这是早期版本中的行为,现在还不确定)。

And I remember having some discussion with CF people on why they don't initialize complex-type properties - vs they still are ok with accessing private members (if I recall correctly), was a long ago. 我记得和CF人讨论过为什么他们没有初始化复杂类型的属性 - 他们仍然可以访问私有成员(如果我没记错的话),很久以前。

So, a bit of general question - but in that sense hope this clarifies something at least. 所以,这是一个普遍的问题 - 但在这个意义上希望这至少可以澄清一些问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM