with ef 4.1 code first how can i create a nullable

2019-08-27 02:25发布

问题:

I have the following POCO:

Public Class T1

<Required()>
<MaxLength(128)>
<Key(), Column(Order:=0)>
Property K1 As String

<Required()>
<MaxLength(128)>
<Key(), Column(Order:=1)>
Property K2 As String

<Required()>
Property C1 As String

Property C2 As String

end Class

I would expect C2 to be created as Nullable, but both C1 and C2 are Not Null. Adding

    <Required(AllowEmptyStrings:=True)>

Does not make a difference, as it seems the decoration is aimed at data validation, not DB creation.

So how do i get a nullable column with Code First?

回答1:

There is no way to say that string property is nullable by attributes because it is default behaviour if you don't mark property with RequiredAttribute. In case of fluent mapping you can describe it as:

context.Entity(Of T1)().Property(Function(t) t.C2).IsNullable(True)