【发布时间】:2013-12-20 21:23:51
【问题描述】:
我正在使用来自 bower 的 Web API 2 和 CORS/Entity Framework 6/Breeze.js 用于单页应用程序,并且微风查询没有扩展导航属性。
我将把它从服务器分解到客户端。
// POCO
public class Foo
{
public int Id { get; set; }
public Bar Bar { get; set; }
}
public class Bar
{
public int Id { get; set; }
public string SomeData { get; set; }
}
public class FooMap : EntityTypeConfiguration<Foo>
{
public FooMap()
{
HasKey(t => t.Id);
ToTable("Foo");
Property(t => t.Id).HasColumnName("Id");
HasRequired(t => t.Bar).WithMany().Map(t => t.MapKey("BarId"));
}
}
// Web API 配置 // 省略静态类和默认路由 // config 是 HttpConfiguration
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
// 微风控制器
[BreezeController]
public class FooController : ApiController
{
readonly EFContextProvider<SomeDbContext> _contextProvider =
new EFContextProvider<SomeDbContext>();
[HttpGet]
public string Metadata()
{
return _contextProvider.Metadata();
}
[HttpGet]
public IQueryable<Foo> Foos()
{
return _contextProvider.Context.Foos;
}
}
// 前端土地
// main.js
breeze.NamingConvention.camelCase.setAsDefault();
var FooService = (function(breeze) {
var service = "http://localhost:58996/breeze/Foos";
breeze.config.initializeAdapaterInstances({ dataService: 'webApi' });
var manager = new breeze.EntityManager(service);
var entityQuery = new breeze.EntityQuery();
this.getAll = function(callback, errorCallback) {
return manager.executeQuery(entityQuery.from('Foo').take(10).expand('Bar'), callback, errorCallback);
};
})(window.breeze);
var fooService = new FooService();
fooService.getAll(function(data) {
console.log(data);
}, function(error) {
console.log(error);
});
Fiddler 显示 JSON 负载:
[
{
"$id":"1",
"$type":"DataAccess.Models.Foo, DataAccess",
"Id":"10",
"Bar":{
"$id":"2",
"$type":"DataAccess.Models.Bar, DataAccess",
"Id":"12",
"SomeData":"Hello World"
}
}
]
但是bar不是chrome数组中对象的字段。
编辑:
解决方法是添加一个属性来保存BarId,并将其设置为外键。
public class Foo
{
public int Id { get; set; }
public int BarId { get; set; }
public Bar Bar { get; set; }
}
public class FooMap : EntityTypeConfiguration<Foo>
{
public FooMap()
{
HasKey(t => t.Id);
ToTable("Foo");
Property(t => t.Id).HasColumnName("Id");
Property(t => t.BarId).HasColumnName("BarId");
HasRequired(t => t.Bar).WithMany().HasForeignKey(t => t.BarId);
}
}
【问题讨论】:
标签: entity-framework asp.net-web-api cors breeze