简体   繁体   中英

Decorating a nullable field as a non-nullable property for code first Linq to SQL

I'm adding Linq to SQL attributes to a pre-existing class (where it would be a breaking change to change the data type of the properties) I did think that specifying the Storage parameter of the ColumnAttribute would instruct the Linq to SQL bits to interact directly with the backing field, so I would expect something like below to work:

Private _foo As Integer? = 0
<Column(CanBeNull:=True, DbType:="INT", Name:="FooBar", Storage:="_foo")> _
<DefaultValue(0)> _
Public Property Foo() As Integer
    Get
        Return If(_foo.HasValue, _foo.Value, 0)
    End Get
    Set(ByVal Value As Integer)
        _foo = If(Value = 0, New Integer?(), Value)
    End Set
End Property

After giving it a whirl, with a basic:

MyThing target = (from u in context.MyThings select u).First();

I'm finding that this fails with:

System.InvalidOperationException: The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type..

So, is it possible to markup the existing code to work with Linq to SQL without making a breaking change, or do I have to add a duplicate property for the LINQ to SQL version?

尝试....

If(IsNothing(_foo), 0, _foo.Value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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