简体   繁体   中英

Adding data using oData service

I am getting an error adding data using OData service. Any help is appreciated.

Entity (The Product table has PK defined on ID column )

     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;
            }

        }

DataSource :-

    /// <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 Service

     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;
            }


        }

Client

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

Exception - On 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;

It looks like you haven't overwritten the SetValue method that IUpdatable requires (but this would actually give you a compilation error, so I guess you've just not included it.) But some important work is done here to actually assign a value to your Id and Name properties, otherwise your Product object added to the the products list will contain null values.

However, the error message says that parameter name "type" is null, so maybe you have a column in your database table called 'type' that isn't nullable?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM