开发者

ASP.NET MVC: How can I serialized data from instance of classes generated by Linq2Sql?

I've learned to create multi-steps application from the Steve Sanderson's book (Pro ASP.Net MVC/APress p.477). Since then, I've adapted that Technique to many scenarios. Basically, it's about serialization/deserialization to keep data live between requests.

But the only problem is I cannot use model generated by Linq2Sql because MVC will complain that those classes are not marked [serializable].

So I do explicit conversion. I create the same class to match the one created by Linq2Sql: So, I get twice the same content with slightly different names. For instance, Client and ClientData, Product and ProductData, Registration and RegistrationData, etc. Each pair contains exactly the same properties.

Example: To process a client instance,

  1. I pull it from the DB using Linq2Sql relying on its id
  2. I convert the Client instance pulled from the DB into a ClientData ins开发者_JS百科tance using a static method, which simply assigns values from one instance's properties to the other's.
  3. After processing I do the reverse: I convert ClientData instance into Client and persist it in the DB using Linq2Sql.

Then I have to write useless code and start to forget which one does what.Question: Is there any techniques I can use to avoid explicit conversion and still be able to serialize data from instances of classes generated by Linq2Sql.

Below is the type of method I use to translate the instance of one type to that of a different one. I have 2 methods, one to get the data and the other to save to the DB.

public static Client Translate_Client_Into_ClientData(Client client)
{
  return new ClientData()
  {
    ClientID = client.ClientID,
    FirstName = client.FirstName,
    LastName = client.LastName
    //And so and so ...
  }
}

It looks like I'm not drying up, rather getting wet... that way.

Thanks for helping


Is it important that they be decorated with [Serializable]? Or merely that they are serializable? If the latter, use the following option with sqlmetal: /serialization:Unidirectional, which will add DataMember and DataContract attributes as appropriate. Another option is to generate your LinqToSql classes yourself. That option offers by far the most power and long term flexibility, but is non-trivial to get going. (I use T4 templates for this)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜