共用方式為


Type Constraints (EDM)

The Entity Data Model (EDM) permits specification of constraints over the properties of its entity types. Constraints restrict the possible values of a property and verify that a value assigned to a property is not only the correct data type but that it is also valid for the business requirements of the application.

Nullable Constraint

Any property can be constrained by using the Nullable constraint. The Nullable constraint is the simplest kind of constraint and specifies whether the value of the property can be unassigned, or Null.

The Key property of an entity is used to identify instances of the type in applications. The Key property must be assigned a value when the entity is created. The Nullable constraint is always required on the property of an entity that contains the Key, and setting the Nullable constraint to false prevents instantiation of entities without identifiers.

The following schema specifies Nullable constraints on properties of the Person type. The EMailID property can be Null, but Name must be assigned a value or a runtime error will result when code saves the type to storage.

    <EntityType Name="Person">
        <Key>
            <PropertyRef Name="Name" />
        </Key>
        <Property Name="Name" Type="String" Nullable="false" />
        <Property Name="EmailID" Type="String" Nullable="false" />
        <Property Name="Address" Type="AddressType" Nullable="true" />
        <Property Name="PhoneNumber" Type="String" />
    </EntityType>

As in SQL Server, the default value of the Nullable attribute is true. Both the Address property and the PhoneNumber property in this example can be unassigned.

Default Attribute

The Default attribute specifies a value for a property if none is supplied when an instance of the entity is created. In the following example the Locale property defaults to NW Region if no other value is supplied when a new Customer is instantiated.

    <EntityType Name="Customer">
        <Key>
            <PropertyRef Name="CustomerId" />
        </Key>
        <Property Name="CustomerId" Type="String" Nullable="false" />
        <Property Name="Name" Type="String" Nullable="false" />
        <Property Name="Locale" Type="String" Default="NW Region"/>
        <!--Other Properties-->
    </EntityType>

See Also

Concepts

GetterAccess and SetterAccess Attributes (CSDL)
Simple Types (EDM)