开发者

How do I create a dynamic data transfer object dynamically from ADO.net model

开发者 https://www.devze.com 2023-02-10 06:50 出处:网络
I have a pretty simple database with 5 tables, PK\'s and relationships setup, etc. I also have an ASP.net MVC3 project I\'m using to create simple web services to feed JSON/XML to a mobile app using p

I have a pretty simple database with 5 tables, PK's and relationships setup, etc. I also have an ASP.net MVC3 project I'm using to create simple web services to feed JSON/XML to a mobile app using post/get. To access my data I'm using an ADO.net entity model class to handle generation of the entities, etc.

Due to issues with serialization/circular references created by the auto-generated relations from ADO.net entity model, I've been forced to create "Data transfer objects" to strip out the relations and data that doesn't need to be transferred.

Question 1: is there an easier way to create DTOs using the entity framework itself? IE, specify only the entity properties I want to convert to Jsonresults? I don't wish to use any 3rd party frameworks if I can help it.

Question 2: A side question for Entity Framework, say I create an ADO.net entity model in one project开发者_StackOverflow社区 within a solution. Because that model relies on the connection to the database specified in project A, can project B somehow use that model with a similar connection? Both projects are in the same solution.

Thanks!


I've been forced to create "Data transfer objects" to strip out the relations and data that doesn't need to be transferred.

And you think that this is something bad? At the contrary that's exactly how a properly designed ASP.NET MVC application should work: it should use view models. And not only for actions returning JSON but for ALL actions. You should avoid passing your EF models to the views. Views should never know of the existence of EF. View models are classes that are specifically designed to meet the requirements of a view. So the controller queries a repository to fetch a model (EF), maps it to a view model and passes it to the view to be shown. To simplify this mapping between your models and view models you could use AutoMapper.


RE: Question 2: The ObjectContext constructor is overloaded to take various EntityConnections and Connection Strings. One of the overloads should get you where you need to be.

0

精彩评论

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