Dion V.
Dion V.

Reputation: 2120

Using a Model from a WCF WebService

Not really sure if the title is correct, but I'll explain it further.

At the moment I have two web applications; one being an ASP.NET MVC 5 application and one being a WCF Service. The WCF Service is a service containing all the business logic and the data access layer. For accessing my database, I use Entity Framework 6.

I am trying to create a Controller for accessing some data in the database through the MVC application. It should have regular CRUD operations for testing purposes. The problem I ran into is that because my DAL is in the WCF Service, I continuously have to cast the retrieved data from the service to a model in my ASP.NET MVC application for it to be shown.

My question is; is it possible to use the EF-generated classes on my WCF Service to function as model in my ASP.NET MVC application?

For clarity, I added some codesamples;

WCF EF-generated object

public class WCFPerson
{
    public string Name { get; set; }
    public int Age { get; set; }
}

WCF Service

[WebMethod]
public List<WCFPerson> GetAllPersons()
{
    using (var db = new SomeDbcontext())
    {
        return db.WCFPersons.ToList();
    }
}

ASP.NET MVC Model

public class Person
{
    [Required]
    public string Name { get; set; }

    [Required, RegularExpression("([0-9]+)")] 
    public int Age { get; set; }
}

ASP.NET MVC Controller

public class PersonController : Controller
{
    private WCFService.WebServiceClient client = new WCFService.WebServiceClient();

    public ActionResult Index()
    {
        var persons = client.GetAllPersons();
        var model = new List<Person>();

        //My problem:
        foreach (var person in persons)
        {
            model.Add(new Person() { Name = person.Name, Age = person.Age });
        }

        return View(model);
    }
}

I find this casting is very annoying. Imagine a scenario where the database changes, nuff said. Also, this example is small - my current Model has about 15 properties and it's very annoying to cast them all.

There is no chance I put the database connection directly in the MVC application. It has to be in the WCF Service for specific reasons. If it would be possible, I would've already done that.

Edit 1: Added DataAnnotations. This is actually quite important.

Upvotes: 3

Views: 1763

Answers (1)

Carles Company
Carles Company

Reputation: 7216

You should be able to use it directly as the model. There is no problem to do it so.

Another thing, to make the conversion you could also use Linq:

model=persons.Select(t=>new Person{
                          Name=t.Name,
                          Age=t.Age
                          });

This way is more compact.

Upvotes: 2

Related Questions