当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Is mapping of data contract to entity of entity framework in wcf is costly operation

问题描述:

While using EF with wcf come across the condition where i need to map entity to data contract and vice versa because EF objects are burdened with additional data provided by EF. So tried few functions for mapping.

[DataContract]

public class WebsitesD

{

[DataMember]

public int Id { get; set; }

[DataMember]

public string Domain { get; set; }

[DataMember]

public string UserId { get; set; }

[DataMember]

public string Title { get; set; }

}

private WebsitesD mapWebsite(Website w)

{

WebsitesD wd = new WebsitesD();

wd.Id = w.Id;

wd.Title = w.Title;

wd.UserId = w.UserId;

wd.Domain = w.Domain;

return wd;

}

public int insertWebsite(WebsitesD d)

{

try

{

using (MyInfoEntities entities = new MyInfoEntities())

{

entities.Websites.Add(mapWebsite(d));

entities.SaveChanges();

return 1;

}

}

catch (Exception e)

{

throw e;

}

}

where WebsitesD is my data contract and website is entity object. With this i can achieve my objective but problem is that whenever i need to perform any database operation i need to do mapping which i think can be costly operation.

Should i leave Entity Framework and go with ADO .net as i don't need to do any mapping over there. Please suggest me pros and cons with which approach i should go.

网友答案:

As with any ORM there is trade-off between performance and developer productivity. As you said ADO.NET will be the fastest method to fill your data contracts from datareader/dataset, with EF/NHibernate you will always have this situation. However mapping is not expensive for solo entities , it becomes expensive when you map list of entities.If you dont need mapping at all , you can also put [DataContract] on entity classes and [DataMember] on members which wcf want to send to client. but when your EF code is autogenerated when your schema changes , that is all wiped out. You can also opt for EF Code First approach.

Another approach which involves less coding for mapping is to use AutoMapper Check this out

Also there is good thread on ORM tradeoffs here

网友答案:

Do what's best for the code base. Consider maintainability and productivity. Servers are cheap and developers are expensive. Very few companies in the world are of such a scale that it is worth maintaining more complicated code rather than buying another server.

网友答案:

With EF 6, you can use the code generation item EF 6.x DbContext Generator with WCF Support.

Just right click on the designer of the EDMX and go to Add Code Generation Item...

Click Online on the left and search for DbContext.

Using this will auto generate the DataMember and DataContract Attributes in your classes. Also, you'll probably want to delete the regular template generated with the edmx, or you will have two sets of entities.

分享给朋友:
您可能感兴趣的文章:
随机阅读: