I have this class:
public class MyClass {
[Column(Name="StoredColumn", DbType="int")]
public int Stored;
public int ForDisplay {
get { return Stored * 1000; }
}
}
The point is ForDisplay
is not to be stored in the database - I just need it for more convenient code.
I try to run an SQL query that returns a rowset and get this InvalidOperationException
:
Cannot assign value to member 'ForDisplay '. It does not define a setter.
I don't want ForDisplay
to be touched by Linq-To-Sql. How do tell Ling-To-Sql to not touch it?
In LINQ, the Except method or operator is used to return only the elements from the first collection, which are not present in the second collection.
LINQ to SQL, when used exclusively for data access, eliminates the possibility of SQL injection in your application for one simple reason: every SQL query that LINQ executes on your behalf is parameterized.
The where clause is used in a query expression to specify which elements from the data source will be returned in the query expression. It applies a Boolean condition (predicate) to each source element (referenced by the range variable) and returns those for which the specified condition is true.
You don't need to tell Linq to Sql that it should not touch the "ForDisplay" property. Normally, all properties that are not specifically marked with the Column
attribute are treated as transient part of your application logic and are not persisted or retrieved from the database.
However, if you want to retrieve some records from the database via a stored procedure, say GetMyClasses
, then the designer will create a new class GetMyClassesResult
. If you look at the generated code, then you will notice that the class is not decorated with the Table
attribute. In that case the mapper assumes that every property must be assigned. If there is a property without corresponding value in the query then the mapper will try to set the property to default(T), but as there is no setter, the exception will be thrown.
Anyway, to make a long story short, just adding
[Table]
public class MyClass
{
...
}
to your class should fix the issue.
You can extend linq2sql with partial classes. The key element is not to modify the original class but create an extra partial class:
public partial class MyClass
{
public int ForDisplay {
get
{
return this._Stored * 1000;
}
}
}
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