David Rasuli
David Rasuli

Reputation: 832

Entity Framework and WCF Data Members

1)

I have a Entity Framework (v.5) project which works with WCF.

My database has an Account table , and therefore I have an "Account" entity framework object. I'd like to expose a method:

 AddAccount(Account a)

The Account Parameter is an entity framework object generated from my DataBase.

Each time that I try to consume this Service, the properties of Account are empty, and I can't understand why.

Here is an example of my code :

WCF :

Interface:

[OperationContract(Name = "AddAccount")]
string AddAccount(Account Account);

Implement:

public string AddAccount(Account newAccount)
{
    myContext db=new myContext();
    db.Accounts.Add(newAccount);
    db.SaveChanges();
    return "something";
}

Account Class is generated by the EF, and has an int "id" field, and DateTime "Created" field.

My question is, why is the "newAccount" parameter is empty?

2)

From what I know, the best way to expose a method with complex parameters is using DataContract and DataMembers , and that raises two questions that I'd like to ask.

a)Do I need to implement DataContract to an Entity object ? From what I understood its not recommanded to expose an EF object directly, but use DataContract on the class I'd like to transfer, but on the other hand, I get no error while trying to use my project , which doesn't implement DataContract on Account.

b) Why isn't it recommanded to pass EF object as parameters, besides letting the client understand my Database table's build?

Thanks.

Upvotes: 1

Views: 719

Answers (1)

Lajos Arpad
Lajos Arpad

Reputation: 77022

In your database you can assign identity specification to the id field and you can give a default value to your created field.

If you have the columns of id and created, you need to initialize Created. You don't need to initialize your id field unless it has no identity specification in your database. In general you need to initialize your values, because your database is not able to guess what values should be assigned to your properties.

So your entity is not created by the database, it is created by your method and it is empty, because you didn't initialize it. Example initialization

public string AddAccount()
{
    myContext db=new myContext();
    //id is not initialized, because I'm assuming it has an identity specification
    db.Accounts.Add(new Account() { Created = DateTime.Now.ToUniversalTime()});
    db.SaveChanges();
    return "something";
}

Your entity class doesn't need to implement DataContract, my projects work impeccably using EF objects which are instances of classes which don't implement DataContract.

You can pass EF objects as parameter in your business logic, there is absolutely no problem with that. You only have to be careful to not let your clients know what the schema of your database is.

I hope this helps.

Upvotes: 1

Related Questions