通过在context中设置可以追踪EF中生成的sql
public BookServiceContext() : base("name=BookServiceContext") { // 当然也可以输出到其它位置 this.Database.Log = s => System.Diagnostics.Debug.WriteLine(s); }
下面的Book类与Author类构成互相引用,在序列化时会遇到“Self referencing loop detected with type ‘BookService.Models.Book‘”问题
1 public class Book 2 { 3 public int Id { get; set; } 4 public decimal Price { get; set; } 5 public string Genre { get; set; } 6 7 // Foreign Key 8 public int AuthorId { get; set; } 9 // Navigation property 10 public Author Author { get; set; } 11 } 12 13 public class Author 14 { 15 public int AuthorId { get; set; } 16 [Required] 17 public string Name { get; set; } 18 19 public ICollection<Book> Books { get; set; } 20 }
解决方案:
- 使用DTOs
- 配置XML或Json的序列化器,使其能够处理循环引用
Model-View-ViewModel(MVVM)模式:
- model 代表服务端的业务数据
- view 表示层(html)
- view model 是JavaScript对象持有的model
时间: 2024-10-17 00:49:39