Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL and immutability

I'm tryign to use LINQ to SQL. Everythign works great but it seems that it is not friendly to immutable objects.

LINQ to SQL requires me to create a parameterless constructor for my immutable class. But I want it to be immutable, so I want to only allow people to create it with all the required parameters each time.

Likewise I need to have setters on all of my members.

Is there a way that I can still use LINQ 2 SQL without giving up my immutability?

Here is my code:

DataContext db = new DataContext("myconnectistring");
Table<MyImmutableType> myImmutableObjects = db.GetTable<MyImmutableType>();

It will throw exceptions about no setter and no default constructor with no parameters.

like image 897
wcf guru needed Avatar asked Nov 03 '10 16:11

wcf guru needed


1 Answers

You can create types without this ctor, and simpy use the selector to project into them. Since you obviously aren't using updates etc it shouldn't matter that they aren't part of the generate model:

from cust in db.Customers
     ...
     select new ImmutableCust(
         cust.Id, cust.Name, ...);

(where ImmutableCust isn't part of the L2S model)

like image 143
Marc Gravell Avatar answered Oct 12 '22 03:10

Marc Gravell