S.V.
S.V.

Reputation: 1221

Exposing Entity Framework data types over WCF

Edit: I don't know how you guys do this, but this question is indeed a duplicate. See above.

at the moment what I have on my hands is a WCF service that exposes a few basic operations:

public interface IUniService
{
    [OperationContract]
    bool IsUser(string userName);

    [OperationContract]
    User GetUserByUsername(string userName);
}

I also have an Entity Framework database running. Here's a bit of code that accesses the server.

public bool IsUser(string userName)
{
    using (UniDBEntities db = new UniDBEntities())
    {
        User a = new User();
        var user = db.Users.Where(p => p.UserName == userName).ToList();
        return (user.Count() != 0);
    }
}

But the question I have is, I want to expose via the WCF service, some of the classes that are currently in my Entity Framework. When I write a function like:

User GetUserById(int id)

when I return the result, it doesn't seem as though my client has any idea what the User class is. How do I expose my entities as Datamembers?

Upvotes: 1

Views: 567

Answers (1)

gbjbaanb
gbjbaanb

Reputation: 52679

I don't think you can transparently disconnect EF objects from the db easily, however you can create a dto or poco and send that over the network. For reads is not a problem, you send read-only data, for writing to the db, either create method dedicated to updating data, or you can take the EF object, send and receive a copy, suitably wrapped as poco/dto, and then update it with the changes.

It's probably better though to model your middle tier differently to the db schema however, make ita domain model so there's not a 1 to 1 mapping between wcf methods and EF objects. Then you can make your wcf model more appropriate for the caller.

Look up the repository pattern as an example.

Upvotes: 1

Related Questions