简体   繁体   English

只读字段或属性

[英]Readonly Fields or Properties

Is there a way to have either a read only Field or a Property with no setter map to a database column with Entity Framework Code First? 有没有办法让一个只读字段或一个没有setter映射的属性到一个具有Entity Framework Code First的数据库列?

I found both are ignored, example: 我发现两者都被忽略了,例如:

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
    }
}

Is there Fluent API call or another approach to accomplish? 是否有Fluent API调用或其他方法来完成?

There's no way to make entities truly immutable, but you can use an inaccessible setter to stop users from modifying them, which might be good enough, depending on your situation: 没有办法让实体真正不可变,但你可以使用一个无法访问的setter来阻止用户修改它们,这可能已经足够好了,具体取决于你的情况:

public string Address1 // Public Property without a Setter
{
  get { return _address1; }
  internal set { _address1 = value; }
}

The Entity Framework will still be able to set the value, so it'll load properly, but once created the property will be more or less fixed. 实体框架仍然可以设置值,因此它将正确加载,但一旦创建,该属性将或多或少地固定。

(I recommend using an internal rather than private setter, so that you can still perform mappings with the Fluent API in your context or a configuration class, provided they're in the same assembly, or a friend assembly.) (我建议使用internal而非private setter,这样您仍然可以在上下文或配置类中使用Fluent API进行映射,前提是它们位于同一个程序集或朋友程序集中。)

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

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