views:

20

answers:

1

Some of the properties in a class generated by EF are nullable, and some arent.

My first instinct was that this should be driven by Nullable property returned by sp_help MyView. But that doesn't seem to be the case.

Some of my types that are returned as Nullable by sp_help get generated as Nullable , while others, get generated as just bool instead of Nullable*bool*

what is it driven by, and is there any way to control it by the view?

as a test i created ViewA and than ViewB which selected all the columns from ViewA. To my astonishment, entities created from those views were not identical. Some properties were nullable only in ViewB.

+1  A: 

Your hunch is correct, EF create Nullable properties based on your store schema and Views are not an exception to this. In other words, the generated entity object should (and will) exactly reflect your View schema and there is a way that you can find the problem:

First you need to make sure that the DB View has been correctly imported to your model:
For that, crack open your EDM in the XML Editor, go to the SSDL content and find <EntityType Name="yourDbViewName"> then look at the <Property Name="yourFieldName" Type="int" Nullable="false" /> make sure every field has the correct value for Nullable attribute. Since the default value is true, EF, will only put this attribute if it's a NOT Null field.

As of EF4, VS2010 uses a T4 template to generate Entity Objects. Drilling into this T4 reveals how the objects being generated in terms of Nullablity:

private void WritePrimitiveTypeProperty(EdmProperty primitiveProperty, CodeGenerationTools code)
    {
        MetadataTools ef = new MetadataTools(this);
#>

    /// <summary>
    /// <#=SummaryComment(primitiveProperty)#>
    /// </summary><#=LongDescriptionCommentElement(primitiveProperty, 1)#>
    [EdmScalarPropertyAttribute(EntityKeyProperty=<#=code.CreateLiteral(ef.IsKey(primitiveProperty))#>, IsNullable=<#=code.CreateLiteral(ef.IsNullable(primitiveProperty))#>)]
    [DataMemberAttribute()]
    <#=code.SpaceAfter(NewModifier(primitiveProperty))#><#=Accessibility.ForProperty(primitiveProperty)#> <#=code.Escape(primitiveProperty.TypeUsage)#> <#=code.Escape(primitiveProperty)#>

As you can see EF uses MetadataTools to determine if the properties are Nullable and MetadataTools basically contains helper methods that access the Entity Framework metadata needed for code generation which means it looks at your EDM to get this information. Of course you can change this template and customize it, but for the intention of controlling Nullable types based on your DB View, you don't need to since it's already there.

Morteza Manavi