New Posts New Posts RSS Feed: Add and Save
  FAQ FAQ  Forum Search   Calendar   Register Register  Login Login

Add and Save

 Post Reply Post Reply
Author
adamh View Drop Down
Newbie
Newbie


Joined: 07-Jun-2010
Location: New Zealand
Posts: 4
Post Options Post Options   Quote adamh Quote  Post ReplyReply Direct Link To This Post Topic: Add and Save
    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




Back to Top
GregD View Drop Down
IdeaBlade
IdeaBlade
Avatar

Joined: 09-May-2007
Posts: 374
Post Options Post Options   Quote GregD Quote  Post ReplyReply Direct Link To This Post 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);
    }

Back to Top
 Post Reply Post Reply

Forum Jump Forum Permissions View Drop Down