在WCF REST服务中使用EF - SerializationException

时间:2017-01-17 16:29:46

标签: c# entity-framework rest wcf

  

抛出异常:' System.Runtime.Serialization.SerializationException'在System.Runtime.Serialization.dll

当我尝试使用EF从数据库获取FK数据时,这是我得到的错误。

这是我的Context类:

public class Context : DbContext
{

        public DbSet<TypeCar> TypeCarList { get; set; }

        public DbSet<Car> CarList{ get; set; }
}


    [DataContract]
    public class TypeCar
    {
        [DataMember]
        [Key]
        public int TypeCarId{ get; set; }
        [DataMember]
        public string typeName{ get; set; }

    }

    [DataContract]
    public class Car
    {
        [DataMember]
        [Key]
        public int CarId { get; set; }
        [DataMember]
        public string carName{ get; set; }
        [DataMember]
        public virtual TypeCar FK_Car{ get; set; }
    }

这是我的IService界面:

public interface IService1
{

    [OperationContract]
    [WebInvoke(Method = "GET", UriTemplate = "getCars",
      RequestFormat = WebMessageFormat.Json,
      ResponseFormat = WebMessageFormat.Json,
      BodyStyle = WebMessageBodyStyle.Bare)]
    List<Car> getCars();

    [OperationContract]
    [WebInvoke(Method = "GET", UriTemplate = "getTypeCars",
      RequestFormat = WebMessageFormat.Json,
      ResponseFormat = WebMessageFormat.Json,
      BodyStyle = WebMessageBodyStyle.Bare)]
    List<TypeCar> getTypeCars();


}

这是我的Service1类:

public class Service1 : IService1
{


    public List<Avtomobil> getCars()
    {
        using (var db = new Context())
        {
            return db.CarList.ToList();
        }
    }
    public List<TypeCar> getTypeCars()
    {
        using (var db = new Context())
        {
            return db.TypeCarList.ToList();
        }
    }
}

当我调用REST方法getTypeCars时,它的工作方式应该如此。但是当我调用getCars方法(使用FK)时,它会抛出给定的异常(序列化异常)。我尝试了与其他实体相同,但总是相同(当调用带有FK的实体时例外)。

编辑: 如果我删除&#34;虚拟&#34;来自属性FK_TypeCar的单词,不抛出异常,但FK_TypeCar的值为null。

1 个答案:

答案 0 :(得分:1)

@Rabban是正确的 - 您应该使用单独的对象通过EF返回数据,然后将它们转换为您的DataContract对象。以下是其中一个原因之一:

目前,您已为[{1}} virtual创建了Car属性的TypeCar属性,但ICollection<Car>中的TypeCar没有对应Car - 很多关系回到import java.io.*; import java.util.*; public class App { public static void main(String[] args) { String terminate = "X"; String Question = ""; System.out.println("I am the all-knowing Magic 8 Ball!"); do { Scanner scnr = new Scanner(System.in); System.out.println(""); System.out.println("Ask your question here or enter 'X' to exit:"); Question = scnr.nextLine(); continueGame(Question); } while (terminate != Question); String testData[] = {"test1", "test2", "test3"}; writeFile(testData, "data.txt"); ArrayList<String> fileContents = readFile("data.txt"); if (terminate.equalsIgnoreCase(Question)) { for (String contents : fileContents) { System.out.println(contents); } } } public static void continueGame(String Question) { char terminate = 'X'; char condition = Question.charAt(0); if (condition == terminate) { System.out.println(""); System.out.println("Thanks for playing!"); System.exit(0); } try { Random rand = new Random(); int choice; choice = 1 + rand.nextInt(20); responseOptions(choice, Question); } catch (Exception e) { System.out.println("Error: Invalid"); } } public static void responseOptions(int choice, String answer) { switch (choice) { case 1: answer = "Response: It is certain"; break; case 2: answer = "Response: It is decidely so"; break; case 3: answer = "Response: Without a doubt"; break; case 4: answer = "Response: Yes, definitely"; break; case 5: answer = "Response: You may rely on it"; break; case 6: answer = "Response: As I see it, yes"; break; case 7: answer = "Response: Most likely"; break; case 8: answer = "Response: Outlook good"; break; case 9: answer = "Response: Yes"; break; case 10: answer = "Response: Signs point to yes"; break; case 11: answer = "Response: Reply hazy, try again"; break; case 12: answer = "Response: Ask again later"; break; case 13: answer = "Response: Better not tell you now"; break; case 14: answer = "Response: Cannot predict now"; break; case 15: answer = "Response: Concentrate and ask again"; break; case 16: answer = "Response: Don't count on it"; break; case 17: answer = "Response: My reply is no"; break; case 18: answer = "Response: My sources say no"; break; case 19: answer = "Response: Outlook not so good"; break; case 20: answer = "Response: Very doubtful"; break; } System.out.println(""); System.out.println(answer); } public static void writeFile(String arrayToWrite[], String filename) { try { PrintWriter wordWriter = new PrintWriter("filename.txt"); for (String words : arrayToWrite) { wordWriter.println(words + "\n"); } } catch (Exception e) { String msg = e.getMessage(); System.out.print(msg); } } public static ArrayList<String> readFile(String filename) { ArrayList<String> fileContents = new ArrayList(); File myFile = new File(filename); try { Scanner scnr = new Scanner(myFile); String tempStr = ""; while (scnr.hasNextLine()) { tempStr = scnr.nextLine(); fileContents.add(tempStr); } } catch (Exception e) { String msg = e.getMessage(); System.out.println(msg); } return fileContents; } } 。所以关系没有完全描述。如果你这样做,那么WCF DataContractJsonSerializer会因为循环引用而抛出SerializationException。因此,为了使EF实体能够完全描述您的底层模式并使您能够通过WCF将对象传回,您必须创建单独的DTO。