使用oData服务添加数据

时间:2012-05-28 23:48:29

标签: c# linq odata

使用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();
                    }
                }

            }

OData服务

     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;

1 个答案:

答案 0 :(得分:0)

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

但是,错误消息显示参数名称“type”为null,那么您的数据库表中是否有一个名为“type”的列不可为空?