例如,我有一个名为Product的列表,它具有3列,即ProductName(即标题),ProductPrice和ProductType。


ProductName是一个字符串
ProductPrice是一种货币(双精度)
ProductType是ProductTypes列表上的Lookup


通常,如果它不包含LookUp列,这对我来说很容易,但是我不知道插入时如何处理查找列。

我尝试过此操作,但返回错误Specified cast is not valid.

这是当前代码

EntityList<ProductTypeItem> ProductTypes = dc.GetList<ProductTypeItem>("ProductType");

ProductItem newProduct = new ProductItem();

newProduct.Title = txtProductName.Text;
newProduct.ProductPrice = double.Parse(txtProductPrice.Text);
newProduct.ProductType = (from a in ProductTypes where a.Title == ddProductType.SelectedItem.Text select a).FirstOrDefault();

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


我将如何处理newProduct.ProductType,因为这是发生错误的地方。

请注意,ddProductType数据源是ProductType列表,并且在其TitleDataTextField中使用DataValueField

最佳答案

This可能会帮助您。第一个示例说明了插入如何与现有数据的链接一起使用。此示例代码应为您提供足够的提示,以帮助您解决问题:

AdventureWorksDataContext db = new AdventureWorksDataContext();

// LINQ query to get StateProvince
StateProvince state = (from states in db.StateProvinces
                       where states.CountryRegionCode == "AU" && states.StateProvinceCode == "NSW"
                       select states).FirstOrDefault();
// LINQ function to get AddressType
AddressType addrType = db.AddressTypes.FirstOrDefault(s => s.Name == "Home");

Customer newCustomer = new Customer()
{
    ModifiedDate= DateTime.Now,
    AccountNumber= "AW12354",
    CustomerType='I',
    rowguid= Guid.NewGuid(),
    TerritoryID= state.TerritoryID    // Relate record by Keys
};
Contact newContact = new Contact()
{
    Title = "Mr",
    FirstName = "New",
    LastName = "Contact",
    EmailAddress = "[email protected]",
    Phone = "(12) 3456789",
    PasswordHash= "xxx",
    PasswordSalt= "xxx",
    rowguid = Guid.NewGuid(),
    ModifiedDate = DateTime.Now
};
Individual newInd = new Individual()
{
    Contact= newContact,    // Relate records by objects (we dont actually know the Keys for the new records yet)
    Customer= newCustomer,
    ModifiedDate= DateTime.Now
};
Address newAddress = new Address()
{
    AddressLine1= "12 First St",
    City= "Sydney",
    PostalCode= "2000",
    ModifiedDate=DateTime.Now,
    StateProvince= state,
    rowguid = Guid.NewGuid()
};

// Link our customer with their address via a new CustomerAddress record
newCustomer.CustomerAddresses.Add(new CustomerAddress() { Address = newAddress, Customer = newCustomer, AddressType = addrType, ModifiedDate = DateTime.Now, rowguid = Guid.NewGuid() });

// Save changes to the database
db.SubmitChanges();

关于c# - LINQ to Sharepoint InsertOnSubmit问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5174225/

10-08 20:34