0

Within Sharepoint, I have a Products list and a Categories list. I'm trying to create a new (Product) item from a web form. The Product list has a Category lookup column, and when i try to create a new instance of Product, I get a null reference error on my insert. I read a post that the item needs to be created with the non-lookup column values, retrieve the new item's id, then insert the value into the lookup column, but I get the same error. Can anyone help with the correct way to do this?

ProductDevelopmentDataContext dc = new ProductDevelopmentDataContext(SPContext.Current.Web.Url);
EntityList<ProductItem> Product = dc.GetList<ProductItem>("Product");

ProductItem newProduct = new ProductItem();
newProduct.Title = title.Text;
newProduct.ProductDescription = description.Text;

dc.Product.InsertOnSubmit(newProduct);
dc.SubmitChanges();

var newProductID = (int)newProduct.Id;
ProductDevelopmentDataContext newdc = new ProductDevelopmentDataContext(SPContext.Current.Web.Url);

newProduct = (from p
        in newdc.Product
        where p.Id == newProductID
        select newProduct).Single();
newProduct.CategoryName.Title = category.Text;

newdc.Product.InsertOnSubmit(newProduct);
newdc.SubmitChanges();
4

1 回答 1

0

This is because newProduct.CategoryName is null. Rather than assigning the lookup title, assign the object itself:

newProduct.CategoryName = category

Then all you need to do is SubmitChanges(). Calling InsertOnSubmit again will create a new record.

Also you don't need to create two ProductDevelopmentDataContext objects, just use dc for all the commands.

Edit: To get the CategoryItem object:

newProduct.CategoryName = (from c
        in dc.Categories
        where c.Title == category
        select new c).First();
于 2013-03-29T21:58:36.810 回答