Mike Taulty's Blog
Bits and Bytes from Microsoft UK
ADO.NET Data Services - Inserting Related Entities

Blogs

Mike Taulty's Blog

Elsewhere

I spent some time with ADO.NET Data Services sitting atop of Entity Framework today trying to insert some related entities and I kept hitting problems that I couldn't figure out.

I was looking at the QuickStart here;

http://quickstarts.asp.net/3-5-extensions/adonetdataservice/NETClientLibrary.aspx

and, specifically, the sample that adds a new Product to an existing Category.

I wasn't using Product and Category. I was using Book and Author. My tables look like this;

create table author
(
  id int primary key not null,
  firstName nvarchar(30) not null,
  lastName nvarchar(30) not null
)

create table book
(
  id int primary key not null,
  authorId int foreign key references author(id) not null,
  title nvarchar(100) not null,
  price money not null
)

So, they are very basic and I inserted some simple data and then just added them to an Entity Framework EDM model within a WebSite project and then I added an ADO.NET Data Service on top of that. I then used the webdatagen.exe tool to generate some client side code and wrote something like this;

    demoEntities efService = new demoEntities("http://localhost:32767/WebSite6/EFService.svc");
      efService.MergeOption = Microsoft.Data.WebClient.MergeOption.AppendOnly;

      var author = (from a in efService.author
                   where a.firstName == "Charles"
                   select a).First();

      book b = new book()
      {
        id = 5,
        price = 4.99m,
        title = "Hard Times"
      };
      efService.AddObject("book", b);
      b.author = author;
      efService.AddBinding(b, "author", author);

      efService.SaveChanges();

 

We select out an existing author, add a new book and then SaveChanges(). It all seems fine (and it matches the QuickStart pretty much exactly) but it didn't work. I kept getting server-side errors about not being able to perform the insert of the book without an author.

In the end, this turned out to be related to my not null constraint on the foreign key in my book table. What I find the framework doing for this particular client code is;

  1. Insert the book
  2. Update the book to set the author id

Now, that's not going to work for my case where my authorId is marked as not null.

At the time of writing, I'm not sure if there's something that I can do on the client-side to make this work for the situation where authorId is marked as non null but, for now, I've just made it nullable - I'll update the post if I get more definitive information.


Posted Wed, Jan 2 2008 11:06 AM by mtaulty
Filed under: ,

Comments

Christopher Steen wrote Link Listing - January 2, 2008
on Wed, Jan 2 2008 9:49 PM
ASP.NET  Weird DataGrid Paging Error with Last Page Selection [Via: Rick Strahl ] Sharepoint  Building...