I'm attempting to re-write a VB.NET WebForms application in C# MVC. I'm having an issue with one of the properties when using Entity Framework to instantiate a class.
I have a column in my database "VATInclusive", which is of type 'int'. The original application implicitly converted a "1" or "0" to "true" or "false", but when trying to do this in my application, I get the following error:
The 'VATInclusive' property on 'Shop' could not be set to a 'System.Int32' value. You must set this property to a non-null value of type 'System.Boolean'.
I can't simply change the type in the database as other applications make use of the table. I've tried using the following code to convert the value, but it seems to only return false, regardless of whether the database has a "0" or a "1"... Can anybody suggest a solution to this?
[Column("VATInclusive")]
private int _VATInclusive { get; set; }
[NotMapped]
public bool VATInclusive
{
get
{
if (_VATInclusive == 0)
{
return false;
}
else
{
return true;
}
}
set
{
if(_VATInclusive == 0)
{
this.VATInclusive = false;
}
else
{
this.VATInclusive = true;
}
}
}
C# Entity framework is an Object Relational Mapping (ORM) framework that gives developers an automated way to store and access databases. The Entity Framework allows developers to work with data at a higher level of abstraction.
Entity Framework (EF) Core is a lightweight, extensible, open source and cross-platform version of the popular Entity Framework data access technology. EF Core can serve as an object-relational mapper (O/RM), which: Enables .NET developers to work with a database using .NET objects.
Entity Framework is an open-source ORM framework for . NET applications supported by Microsoft. It enables developers to work with data using objects of domain specific classes without focusing on the underlying database tables and columns where this data is stored.
Following some advice from the answers provided, I have rectified the issue. The issue lay with the setter accessor and also with the _VATIncusive property. By changing the code to the following I have managed to get the system to work as I expected.
However, I feel that this isn't the best approach, but it appears to be working correctly...
EDIT : EDIT : I've reduced the get accessor as per advice from Ryan and hvd..
EDIT : I'm not sure of the implications of having both properties set to public. But I don't think this is going to be an issue.
[Column("VATInclusive")]
public int _VATInclusive { get; set; }
[NotMapped]
public bool VATInclusive
{
get
{
return _VATInclusive != 0;
}
set
{
_VATInclusive = value ? 1 : 0;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With