Print Page | Close Window

Add and Save

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2010
Forum Discription: For .NET 4.0
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=1972
Printed Date: 30-Apr-2025 at 4:18pm


Topic: Add and Save
Posted By: adamh
Subject: Add and Save
Date Posted: 17-Jul-2010 at 11:52pm
Silverlight

I have an object 'Person' that has a 0 or 1 relationship with an object 'Lunch'  (i.e. it may have 1 or no lunch)
Both 'Person' and 'Lunch' have auto generated 'unique identifier'

I want to either.
Add a 'Lunch' to a 'Person' if they don't have one or modify the 'Lunch' if they do.

I am OK with modifying .. I just modify and call 'SaveChangesAsync'

But if I have a Person that does not have a 'Lunch' it appears as 'detached'

How do I Add and Save a 'Lunch'.

        Lunch lunch = em.CreateEntity<Lunch>();
        lunch.Timestamp = DateTime.Now;
        lunch.Name = "yummy";
        lunch.Person= person;
        lunch.EntityAspect.AddToManager();
        em.SaveChangesAsync(Done, null);

I get a complaint about the foreign key.

System.Data.UpdateException: Entities in 'LogicOnEntities.Lunch' participate in the 'FK_PersonLunch' relationship. 0 related 'Person' were found. 1 'Person' is expected.

The other way I could do it is to work with the 'detached'  Lunch .. but how do I do theta and Save it?

As well as a solution I would be intereste dto know where in the documentation this is cleary explained??

Thanks







Replies:
Posted By: GregD
Date Posted: 21-Jul-2010 at 3:32pm
Not sure what the issue is, but your code above doesn't show where your 'person' value comes from.

In NorthwindIB, Order and Customer are related 0-1. The following code works fine, and reports 1 entity saved. (I've removed the statements that produce the output, as they're specific to my app.)


    public void Test1to1AddAndSave() {
      var customersQuery = _em1.Customers
        .Where(c => c.ContactTitle == "Sales Representative")
        .OrderBy(c => c.CompanyName);
      _em1.ExecuteQueryAsync<Customer>(customersQuery, GotCustomers, null);
    }

    private void GotCustomers(EntityQueryOperation<Customer> args) {
      Order newOrder = _em1.CreateEntity<Order>();
      newOrder.OrderDate = DateTime.Today;
      newOrder.Customer = args.Results.FirstOrDefault();
      _em1.SaveChangesAsync(op => {
        if (op.HasError) {
           // output error message
        }
        else {
           // output count of entities saved // reports "1"
        }
      }, null);
    }




Print Page | Close Window