Entity framework entity class mapping with a plain .NET class - c#

I have the following in Entity Framework.
Table - Country
Fields
List item
Country_ID
Dialing_Code
ISO_Alpha2
ISO_Alpha3
ISO_Full
I would like to map only selected fields from this entity model to my domain class.
My domain model class is
public class DomainCountry
{
public int Country_ID { get; set; }
public string Dialing_Code { get; set; }
public string ISO_3166_1_Alpha_2 { get; set; }
}
The following will work, however insert or update is not possible. In order to get insert or update we need to use ObjectSet<>, but it will not support in my case.
IQueryable<DomainCountry> countries =
context.Countries.Select(
c =>
new DomainCountry
{
Country_ID = c.Country_Id,
Dialing_Code = c.Dialing_Code,
ISO_3166_1_Alpha_2 = c.ISO_3166_1_Alpha_2
});
Is there a nice solution for this? It wound be really fantastic.
Ideally it will be kind of proxy class which will support all the futures however highly customizable.
That is, only the columns we want to expose to the outer world.

The term for "plain .NET classes" is POCO - plain old CLR objects (inspired by POJO, plain old Java objects).
Read this blog post series, it helped me a lot:
http://blogs.msdn.com/b/adonet/archive/2009/05/21/poco-in-the-entity-framework-part-1-the-experience.aspx

I want to do the same thing. My goal is to build a WCF service that can use the same set of objects as the application I'm building by sharing a DLL and sending/receiving the same classes. Additionally, I also wanted to limit what fields are exposed. After thinking about this for a while it seems a user-defined cast might do the trick. Have a look to see if it works for you.
http://www.roque-patrick.com/windows/final/bbl0065.html

Related

Xamarin SQLite using LINQ

I got a sqlite table in xamarain (native android / pcl):
[Table("Customer")]
public class Customer
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public Address Address{ get; set; }
}
"Address" represents a second table.
1) Is it possible to automatically create the "Address" Table when I call
connection.CreateTable<CustomerDto>();
because it is it's dependency?
2) Is it possible to use a LINQ expression which automatically maps the correct "Address" to this "Customer?
In my .NET Standard library I'm using:
"sqlite-net": "1.0.8"
"sqlite-net-pcl": "1.3.1"
My approach was to create "initial state models" of all the tables, marked as abstract (so there is no risk that somebody could instantiate them), defining only the fields necessary in the database and the primary keys (GUID in my case), used only to create tables at the beginning. Following modification to the data structures always with ALTER instructions.
In another namespace a duplication of all the models, this time with getters/setters and other utilities, and I used these as "real models".
For representing linked models I used a field as Id and another one as model (refreshed when necessary):
public int IdAddress { get; set; }
[Ignore]
public Address Address { get; set; }
I don't think sqlite-net can do what you are asking because it's a very lightweight orm, and even if it could I prefer don't automate too much because of my past experiences with Hibernate.
https://github.com/praeclarum/sqlite-net
https://components.xamarin.com/view/sqlite-net
It sounds like you should look at using Entity Framework because that will allow you to use LINQ with SQLite. The standard library on the web (not Entity framework) is very light and doesn't have much functionality for the ORM like functionality you are looking for.
If you're looking for a more lightweight library, you can use this, but it will not allow you to write LINQ expressions without writing your own ORM:
https://github.com/MelbourneDeveloper/SQLite.Net.Standard

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.

Entity Framework native sql mapping to class

I got a code first EF and I want to use native sql for the more complex select statements.
When I try to execute:
using (VaultsDbContext db = new VaultsDbContext())
{
var contracts = db.Contracts.SqlQuery("select * from Contracts").ToList<Contract>();
}
I got:
Cannot create a value for property 'MetaProps' of type
'DskVault.Models.DbModels.MetaProps'. Only properties of primitive or
enumeration types are supported.
MetaProps is a class that holds deleteflag, creator etc. and it's a property of all my classes. It's not mapped to a different table, every table has deleteflag, createor, etc.
public class Contract
{
public long Id { get; set; }
...
public MetaProps MetaProps { get; set; }
}
Is there a way to map from the native sql to the class if the class contains a complex type or does EF not support that? Also what if the complex type is entity mapped to another table(join)?
Edit:
Version: Entity Framework 6
I know from experience not all the fields in your table have to be contained in your model. This is a good thing when it comes to installing updates into production.
Have you tried reverse engineering your tables on a SEPARATE temporary project using the Entity Framework Power tools? This is a Nuget package that I have found to be extremely useful in code first programming. Reverse engineering will overwrite existing files, so make sure not to do this on your live code.

Which ORM should I use together with ServiceStack and an existing database

I am currently developing a web service which provides basic CRUD operations on business objects. The service will be used by legacy applications which currently use direct database access.
I decided to use ServiceStack instead of WCF due to ServiceStacks great architecture.
However know I am trying to decide wether to use OrmLite, nHibernate or Entity Framework to access the existing legacy database.
Requirements for the ORM are as follows
Support for joins
Support for stored procedures
I already tried OrmLite (as it's fast and already included with ServiceStack). The only way I managed to join two tables was by using SQL (not an option). Is there any better way?
// #stackoverflow: This is my POCO DTO
public class Country
{
public long Id { get; set; }
public string Alpha2 { get; set; }
public string Alpha3 { get; set; }
public string ShortText { get; set; }
public string LongText { get; set; }
}
public class CountryRepository : ICountryRepository
{
// #stackoverflow: This is the query to join countries with translated names stored in another table
private const string CountriesSql =
#"SELECT C.Id, C.Alpha2, C.Alpha3, L.ShortText, L.LongText FROM COUNTRY AS C INNER JOIN LOCALIZATION AS L ON C.LocId = L.Id WHERE (L.Lang_Id = {0})";
private const string CountrySql = CountriesSql + " AND C.Id={2}";
private IDbConnection db;
public IDbConnectionFactory DbFactory { get; set; }
private IDbConnection Db
{
get { return db ?? (db = DbFactory.Open()); }
}
public List<Country> GetAll()
{
return Db.Select<Country>(CountriesSql, 0);
}
public Country GetById(long id)
{
return Db.SingleOrDefault<Country>(CountrySql, 0, id);
}
}
The example above shows one of the simple business objects. Most others require Insert, Update, Delete, multiple Joins, and Read with many filters.
If all you need are joins (lazy-loading or eager loading) and stored procedure support and want to get setup quickly then Entity Framework and nHibernate are great options. Here is a cool link about EntityFramework and the repository and unit of work pattern. http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx
If you are very concerned with performance and want more control over how your classes will look (ie POCOs) and behave then you can try something more lightweight like ORMLite or Dapper. These two are just thin wrappers with less features but they will give you the best performance and most flexibility -- even if that means writing some SQL every once in a while.
You can also use hybrid approaches. Don't be afraid to mix and match. This will be easiest when using POCOs.
I think the important thing is to code for your current database and current needs. However, to do so using proper interfaces so if the time came to switch to a different database or storage mechanism then you simply have to create a new data provider and plug it in.
Ormlite supports primitive Join functions using expressions. The new JoinSqlBuilder class can help with this. For SPs, I have added a new T4 file to generate corresponding c# functions. Currently the SP generation code supports Sql Server alone; if you are using any other db, you can easily add support for it.
You might consider LLBLGen Pro -- it's got great support for database first design and also has designer tools that speed up getting started if you use nHibernate or EF. But it is $$.
http://llblgen.com
As a follow up to this Matt Cowan has created an AWESOME template generator for building this sort of thing with LLBLGen. Check out the blog post here:
http://www.mattjcowan.com/funcoding/2013/03/10/rest-api-with-llblgen-and-servicestack/
and demo here:
http://northwind.mattjcowan.com/
The demo is entirely autogenerated!
Also check this comparison from an OO perspective between NHibernate 3.x and Entity Framework 5/6
http://www.dennisdoomen.net/2013/03/entity-framework-56-vs-nhibernate-3.html

EntityFramework, should I use Inheritance?

I have the following model, without using inheritance:
Question class:
public int QuestionId { get; set; }
public string QuestionTitle { get; set; }
public bool Required { get; set; }
public int questionType { get; set; }
[ScriptIgnore]
public virtual ICollection<TextAnswer> TextAnswers { get; set; }
[ScriptIgnore]
public virtual ICollection<ParagraphAnswer> ParagraphAnswers { get; set; }
[ScriptIgnore]
public virtual ICollection<Choice> Choices { get; set; }
[ScriptIgnore]
public virtual ICollection<ChoiceAnswer> ChoiceAnswers { get; set; }
Should I use inheritance for the answers?
That is,
TextAnswer : Answer
ParagraphAnswer : Answer
ChoiceAnswer : Answer
so that the Question class have only one ICollection ?
What would you suggest me?
Yes, the proper way to model this is with inheritance.
Note that you have some choices of how inheritance is mapped to tables (TPH, TPT) and with complex, multilevel hierarchies you may want to keep an eye on performance.
Yes. That's the advantage of Inheritance in JAVA. Through this approach you'll achieve good design for your code.
Your code will be open for new enhancements and extensions with less code changes, since base class alone will be extended for any new ANSWER class and there won't be no changes needed in question class.
My experience with inheritance and entity framework is rather poor. In specific cases (I don't want to go too much into details here) queries produced by EF had like 1Mb in size.. (I'm not talking about the results - just query text!)
Recently (about 6 months) I've started using NHibernate. In my company we have a software that is developed as a product - which means at least 3-4 levels of inheritance for each entity. NHibernate copes really well with it - you might want to give it a try.
As to EF: no don't use inheritance. This project is not mature enough.
//edit because of downvotes:
I've been using Entity Framework from the first release including hardcore things like writing custom "Custom Tool" for Visual Studio to generate code from EDMX files. The custom generator added support for stored procedures and proper lazy loading (which was broken in EF 1.0) and some more.
Then came EF 2.0 and huge changes. I've used EF in several projects. In one of them we had a requirement that all entities have one base class. This was hardcore hacking once again and this was when the case with huge query text occured. If you want to downvote my answer once again feel free to do it, but just because your case wasn't that complicated (if we can call having a base class a complicated case anyway..) doesn't mean that EF is a mature and stable ORM.

Categories