Database Reference
In-Depth Information
public void DeletePayment(Payment payment)
{
using (var context = new EFRecipesEntities())
{
context.Entry(payment).State = EntityState.Deleted;
context.SaveChanges();
}
}
}
5.
To test our service, we'll need a client. Add a new Windows Console Application project to
the solution. Use the code in Listing 9-29 for the client. Add a service reference to the client
by right-clicking the client project and selecting Add Service Reference. You may need to
right-click the service project and select Debug Start Instance to start an instance of
your service before you can add a service reference in the client.
Listing 9-29. A Simple Console Application to Test Our WCF Service
class Program
{
static void Main()
{
var client = new Service1Client();
var payment = client.InsertPayment();
client.DeletePayment(payment);
}
}
If you set a breakpoint on the first line in the Main() method of the client and debug the application, you can step
through the insertion and deletion of a Payment entity.
How It Works
In this recipe, we demonstrate a common pattern for updating disconnected entities where the client is consuming
WCF or Web API services that expose data from Entity Framework.
In the client, we use the InsertPayment() method to insert a new payment into the database. The method returns
the payment that was inserted. The payment that is returned to the client is disconnected from the DbContext. In fact,
in a situation such as this, the context object may be in a different process space or on an entirely different computer.
We use the DeletePayment() method to delete the Payment entity from the database. In the implementation
of this method (see Listing 9-28), we call the Entry() method from the DbContext object passing in an argument of
payment. We then set the State property for this entity to EntityState.Deleted, which marks the object for deletion.
SaveChanges() deletes the payment from the database.
The payment object that we attached for deletion had all its properties set as they were when the object was
inserted into the database. However, because we're using foreign key association , only the entity key, concurrency
property, and TimeStamp property are needed for Entity Framework to generate the appropriate where clause
to delete the entity. The one exception to this rule is when your POCO class has one or more properties that are
complex types. Because complex types are considered structural parts of an entity, they cannot be null. To keep
things simple, you could simply create a dummy instance of the complex type, as Entity Framework is building its
SQL Delete statement from the entity key and concurrency property only. If you leave the complex type property null,
SaveChanges() will throw an exception.
 
Search WWH ::




Custom Search