Saturday, June 30, 2012

Linq with the MVC pattern: a personal point of view (aka a lot of bullshit)

(play this track while reading)


man I love Linq

really, it saves me tons of time and I love it. I use it for everything, in both its syntax: (the sql-like and the lambda-like one).

plus, since when I found custom providers (info here), I am an happy user. rainbows and honey and unicorns everywhere.

until I needed to develop my first serious web app and I choose to model my data layer with linq. 


figure out how to do the simplest things has really been a pain in the ass. but now I'm gonna tell you what beware and how avoid pitfalls, so hey, unicorns and rainbow for you.

the most important thing you must understand is about the datacontext and your instantiated object: in order to have the datacontext understand the changes you made to an object it must be obtained through the same datacontext instance you're calling the SubmitChanges() method.


what does this mean?

simple:


will work like a charm but


will result in no changes!

once you understood the basic concept "DataContext uber alles" everything is perfectly logic and linear: if the object you're manipulating has not been originated by the datacontext you're submitting changes there's no way that the system can track them (and as result no changes will be propagated to the database or whatever your linq provier is targeting).

the second main concept you must bear in mind: Attach an entity is a plague you must avoid. it will cause you more problems than ever, trust me.

I used to rely on the Attach method to update entities: there's a particular Attach() overload that allows you to pass as argument the modified instance and the original one so the datacontext can infere the changes and rainbows and unicorns and ... well you get that.

something like this:


it works!..... until you call the method UpdatePlayer twice in the same scope.. then it's all about complaining that the Entity is already in use and cannot be modified and shit.

well.. screw you, I went with the old school manual assignment and it worked since then like a foxconn underpaid worker:


well, thank you linq for all the good lies on how life is beautiful with the automation: old school sometimes wins.

No comments:

Post a Comment

Hey, thanks for your opinion!