Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/119.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 只读字段或属性_C#_Entity Framework_Ef Code First_Entity Framework 5 - Fatal编程技术网

C# 只读字段或属性

C# 只读字段或属性,c#,entity-framework,ef-code-first,entity-framework-5,C#,Entity Framework,Ef Code First,Entity Framework 5,有没有办法让只读字段或不带setter的属性首先映射到带有实体框架代码的数据库列 我发现两者都被忽略,例如: using System; namespace App.Model { public class Person { string _address1; // Private Field to back the Address Property public string Address1 // Public Property witho

有没有办法让只读字段或不带setter的属性首先映射到带有实体框架代码的数据库列

我发现两者都被忽略,例如:

using System;

namespace App.Model
{
    public class Person
    {
        string _address1; // Private Field to back the Address Property

        public string Address1 // Public Property without a Setter
        {
            get { return _address1; }
        }


         public readonly string Address2; // Public Read Only Field
    }
}

是否有Fluent API调用或其他方法可以实现?

没有办法使实体真正不可变,但您可以使用不可访问的setter来阻止用户修改实体,这可能已经足够好了,具体取决于您的情况:

public string Address1 // Public Property without a Setter
{
  get { return _address1; }
  internal set { _address1 = value; }
}
实体框架仍然能够设置该值,因此它将正确加载,但一旦创建,属性将或多或少地固定


(我建议使用
internal
而不是
private
setter,这样您仍然可以在您的上下文或配置类中使用Fluent API执行映射,前提是它们位于同一程序集或朋友程序集中。)

问得好。纵观
EntityTypeConfiguration
方法,它看起来并不乐观。不幸的是,私有setter从基类继承时被忽略。我正在尝试确定一种与基类不同的方法。
internal
protected
设置器应该可以工作,不是吗?这是我用于只读实体的方法,即使有相当深的继承层次结构,它也非常有效。我的目标是使值不可变。我的数据库表(如CreatedDate)上有审计列,一旦设置了这些列,我就不想更新它们。在插入时,我想控制如何通过函数设置值,因此我不希望字段/属性可更新。任何字段都可以通过反射进行更新(即使是构造函数注入的
只读
字段)。如果有人下定决心要捣乱你的课堂,他们会找到办法的。你所能做的就是清楚地表明你不想让他们这么做。无论如何,作为一种折衷方案,您可以有一个映射到数据库的
private
read/write属性,然后是一个未映射的
public
只读属性,返回其值。这与我的第一个建议并没有本质上的区别,但它确实增加了一层。EF6将包括对CRUD操作存储过程的支持,如果您的时间线可以等待的话,这可能是一种方法。