Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I exclude a member from Linq-To-Sql mapping?

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?

like image 946
sharptooth Avatar asked Dec 07 '11 08:12

sharptooth


People also ask

What is except in LINQ?

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.

How does LINQ prevent SQL injection?

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.

What is where clause in LINQ?

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.


2 Answers

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.

like image 135
afrischke Avatar answered Sep 22 '22 05:09

afrischke


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; 
       }   
    }   
  }
like image 29
Pleun Avatar answered Sep 19 '22 05:09

Pleun