0

使用 OData 服务添加数据时出现错误。任何帮助表示赞赏。

实体(产品表在 ID 列上定义了 PK)

     using System;
        using System.Linq;
        using System.Data.Services.Common;
        /// <summary>
        /// Summary description for Class1.
        /// </summary>
        [DataServiceKey("Id")]
        public class Product
        {
            /// <summary>
            /// Gets or sets the Id.
            /// </summary>
            /// <value>The Id.</value>
            public int Id
            {
                get;
                set;
            }

            /// <summary>
            /// Gets or sets the Name.
            /// </summary>
            /// <value>The Name.</value>
            public string Name
            {
                get;
                set;
            }

        }

数据源 :-

    /// <summary>
        /// TODO: Provide summary section in the documentation header.
        /// </summary>
        public class ProductContext : IUpdatable
        {
            List<Product> products = new List<Product>
            {
                new Product {Id=1,Name="RedBox"},
                new Product {Id=2,Name="BlueBox"},
                new Product {Id=3,Name="BlackBox"},
            };

            public IQueryable<Product> Products
            {
                get
                {
                    return  products.AsQueryable<Product>();
                }
            }


            public object CreateResource(string containerName, string fullTypeName)
            {
                var objectType = Type.GetType(fullTypeName);
                var resource = Activator.CreateInstance(objectType);
                products.Add((Product)resource);
                return resource;
            }

     public void SaveChanges()
            {
                DataTable productsDT = new DataTable();
                foreach (var product in products)
                {
                    DataRow dataRow = productsDT.NewRow();
                    dataRow["Id"] = product.Id;
                    dataRow["Name"] = product.Name;
                    productsDT.Rows.Add(dataRow);
                }

                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
                {
                    using (SqlCommand command = new SqlCommand())
                    {
                        command.CommandText = "Product_Create";
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.Add("@ProductTable", SqlDbType.Structured);
                        command.Parameters[0].Value = productsDT;
                        command.Connection = connection;
                        connection.Open();
                        command.ExecuteNonQuery();
                    }
                }

            }

数据服务

     public class ProductService : DataService<ProductContext>
        {
            List<Product> products = new List<Product>();

            // This method is called only once to initialize service-wide policies.
            public static void InitializeService(DataServiceConfiguration config)
            {
                // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
                // Examples:
                config.SetEntitySetAccessRule("Products", EntitySetRights.All);
                //config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.);
                config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
                config.UseVerboseErrors = true;
            }


        }

客户

    /// <summary>
            /// Defines the program entry point. 
            /// </summary>
            /// <param name="args">An array of <see cref="T:System.String"/> containing command line parameters.</param>
            private static void Main(string[] args)
            {
                try
                {
                    ProductContext productContext = new ProductContext(new Uri("http://localhost:24395/ProductService.svc/"));
                    productContext.AddToProducts(new Product { Id = 4, Name = "BrownBox" });
                    productContext.SaveChanges();
                    var products = from p in productContext.Products
                                   select p;

                    foreach (var p in products)
                    {
                        Console.WriteLine(p.Id.ToString() + "--" + p.Name);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }

                Console.ReadLine();
            }

例外 - 在 SaveChanges()

System.Data.Services.Client.DataServiceRequestException: An error occurred while
 processing this request. ---> System.Data.Services.Client.DataServiceClientExce
ption: <?xml version="1.0" encoding="utf-8" standalone="yes"?>
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
  <code></code>
  <message xml:lang="en-US">An error occurred while processing this request.</me
ssage>
  <innererror>
    <message>Value cannot be null.&#xD;
Parameter name: type</message>
    <type>System.ArgumentNullException</type>
    <stacktrace>   at System.Activator.CreateInstance(Type type, Boolean nonPubl
ic)&#xD;
   at System.Activator.CreateInstance(Type type)&#xD;
   at LearningOData.ODataServices.ProductContext.CreateResource(String container
Name, String fullTypeName) in 
ta.ODataServices\ProductContext.cs:line 50&#xD;
4

1 回答 1

0

看起来你没有覆盖 IUpdatable 需要的 SetValue 方法(但这实际上会给你一个编译错误,所以我猜你只是没有包含它。)但是这里做了一些重要的工作来实际分配一个值您的 Id 和 Name 属性,否则添加到产品列表中的 Product 对象将包含空值。

但是,错误消息说参数名称“type”为空,所以也许您的数据库表中有一个名为“type”的列不可为空?

于 2012-06-06T13:54:21.257 回答