LINQ to SQL and immutability

ぐ巨炮叔叔 提交于 2019-12-13 13:07:42

问题


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.


回答1:


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)



来源:https://stackoverflow.com/questions/4089012/linq-to-sql-and-immutability

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!