WCF, Entity Framework

In my last post, we saw how to Serialize Object to XML and Deserialize XML to Object using a generic function, now we will see how to save the deserialized object in a database using entity framework.

The source code is here!.

First I created a database called “WCF” with SQL Server 2012 Express, and created a table called Categories

USE [WCF]
GO
/****** Object:  Table [dbo].[Categories]    Script Date: 7/14/2014 7:17:26 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Categories](
	[CategoryID] [int] NOT NULL,
	[CategoryName] [nvarchar](15) NOT NULL,
	[Description] [ntext] NULL,
 CONSTRAINT [PK_Categories] PRIMARY KEY CLUSTERED 
(
	[CategoryID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

Now with the same solution, I add another class project for my EntityFramework called “WcfServicesXmlSample.DO”, and add the table as a Entity

alt tag

Now we need to create our ViewModel

[DataContract]
public class CategoriesViewModel
{       
    [DataMember]
    public int CategoryID { get; set; }
    [DataMember]
    public string CategoryName { get; set; }
    [DataMember]
    public string Description { get; set; }
}

In my interface I add my method

[OperationContract]
Task<CategoriesViewModel> CategoriesDeSerialize(string xmlString);

Our method inheritance from Interface

public async Task<CategoriesViewModel> CategoriesDeSerialize(string xmlString)
{       
    if (xmlString == null)
    {
        throw new ArgumentNullException("categories");
    }
    try 
    {
        CategoriesViewModel categories = GenericDataContractSerializer<CategoriesViewModel>.DeserializeXml(xmlString);
        var result = Mapper.Map<CategoriesViewModel, Category>(categories);
		
        using (var context = new WCFEntities())
        {                 
            bool categoryAvailable = context.Categories.Any(x => x.CategoryID == result.CategoryID);

            if (categoryAvailable == false)
            {
                context.Categories.Add(result);
                await context.SaveChangesAsync();
                return categories;
            }
            else 
            {
                context.Categories.Attach(result);
                context.Entry(result).State = EntityState.Modified;
                await context.SaveChangesAsync();
                return categories;               
            }                       
        }               
    }
    catch (Exception ex)
    {
        throw new ArgumentNullException("Error to Save.", ex);
    }
}

So as you can see, I’m using Automapper to mapping my Entity to my ViewModel, also I added a condition if the ID of the XML already exist, just Update the data, otherwise, saved as a new record.

And the XML input should be like this:

<Categories>
    <CategoryID>3</CategoryID>
    <CategoryName>Hello World</CategoryName>
    <Description>Hello World Description</Description>
</Categories>