实体框架 - 使用数据注释的属性的默认值

时间:2011-06-08 01:24:04

标签: c# asp.net asp.net-mvc entity-framework data-annotations

我有这样的模型

public class MyModel
{
    public int MyModelId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Title { get; set; }
}

我想知道是否有一种方法,使用数据注释,设置属性的值 - 比如标题 - 默认为其他属性值,即名称。类似的东西:

if(MyModel.Title == "") MyModel.Title = MyModel.Name;

3 个答案:

答案 0 :(得分:10)

如果您想要默认值,请在实体默认(无参数)构造函数中设置它。您无需直接进行数据注释。

答案 1 :(得分:4)

你可以告诉实体框架,数据库将通过在edmx文件的SSDL中编辑该属性来处理该属性。

首先

<Property Name="CompanyName" Type="nvarchar" Nullable="false" MaxLength="40" />

我们已将其更改为

<Property Name="CompanyName" Type="nvarchar" Nullable="false" MaxLength="40" StoreGeneratedPattern="Computed" />

通过设置storeGeneratedPattern =“Computed”,我们可以告诉EF,DB将插入属性值。

编辑SSDL

  1. 右键单击edmx文件,使用XML(文本)编辑器打开。
  2. 2.Ctrl + F属性的名称,只需更改该属性

    我不知道有没有办法处理数据注释。

答案 2 :(得分:0)

一般情况下,将属性参数设置为函数是不可能的,您将收到错误:

“属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式”

相关问题