从ADO.NET实体模型序列化生成的类

时间:2014-03-30 13:15:22

标签: c# asp.net entity-framework serialization ado.net-entity-data-model

我有下表:

create table Movie
(
    id integer primary key identity(1,1),
    title varchar(40),
    synopsis varchar(200),
    movieLength integer,
    imageSmall varbinary(max),
    imageLarge varbinary(max),
    inputDate date,
);

使用ADO.NET实体模型,我生成了C#类。

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace CinemaService
{
    using System;
    using System.Collections.Generic;

    public partial class Movie
    {
        public Movie()
        {
            this.Show = new HashSet<Show>();
        }

        public int id { get; set; }
        public string title { get; set; }
        public string synopsis { get; set; }
        public Nullable<int> movieLength { get; set; }
        public byte[] imageSmall { get; set; }
        public byte[] imageLarge { get; set; }
        public Nullable<System.DateTime> inputDate { get; set; }

        public virtual ICollection<Show> Show { get; set; }
    }
}

我有以下合同:

namespace CinemaService
{
    [ServiceContract]
    public interface ICinemaService
    {
        [OperationContract]
        Movie[] list_movies();
    }
}

服务:

namespace CinemaService
{
    [ServiceBehavior]
    public class CinemaService : ICinemaService
    {
        private CinemaEntities _entities;

        public CinemaService()
        {
            _entities = new CinemaEntities();
        }

        public Movie[] list_movies()
        {
            return _entities.Movie.ToArray();
        }

    }
}

该服务托管在IIS上。

当表为空时,我可以调用并获得结果(空结果),但是当有一行时,我得到一个异常。

我在web.config中启用了跟踪,我认为问题是生成的类不可序列化。

使用跟踪查看器,我发现了以下内容:

异常类型:

  

System.ServiceModel.CommunicationException,System.ServiceModel,   Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089

消息:

  

尝试序列化参数时出错   http://tempuri.org/:list_moviesResult。 InnerException消息是   '类型   'System.Data.Entity.DynamicProxies.Movie_46EC56490AEEEA50CA29379C6E09B01C345ECBB1273756AE368BA72AA30754B5'   与数据合同名称   'Movie_46EC56490AEEEA50CA29379C6E09B01C345ECBB1273756AE368BA72AA30754B5:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies'   不是预期的。考虑使用DataContractResolver或添加任何   静态地知道已知类型列表的类型 - 例如,   通过使用KnownTypeAttribute属性或将它们添加到   传递给DataContractSerializer的已知类型列表。'。请参阅   InnerException以获取更多详细信息。

如果需要更多详细信息,请与我们联系。

2 个答案:

答案 0 :(得分:1)

虽然您可以使用多个方法(如注释中所述)(禁用代理生成)来实现您想要的功能。

如果您的架构允许,我建议您使用DTOs(数据传输对象)和automapper等映射工具。

答案 1 :(得分:0)

以下是我解决它的方法:

我删除了生成的类,并下载了一个新的代码生成项模板:EF 6.x EntityObject Generator。 (我使用了DBContext生成器)。

现在工作正常。