我正在使用ODATA开发Asp .Net Core 2.2应用程序。我有测试应用程序来重现该问题: 我无法通过ODATA请求通过链接表向链接的实体发送请求。
请求:/ odata / Books?$ expand = BookCategories
响应错误:
"Message": "The query specified in the URI is not valid. Property 'BookCategories' on type 'GameStorageView.Data.Book' is not a navigation property or complex property. Only navigation properties can be expanded.",
"ExceptionMessage": "Property 'BookCategories' on type 'GameStorageView.Data.Book' is not a navigation property or complex property. Only navigation properties can be expanded.",
"ExceptionType": "Microsoft.OData.ODataException",
型号:
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public ICollection<BookCategory> BookCategories { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public ICollection<BookCategory> BookCategories { get; set; }
}
public class BookCategory
{
public int BookId { get; set; }
public Book Book { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
模型创建:
modelBuilder.Entity<BookCategory>()
.HasKey(bc => new {bc.BookId, bc.CategoryId});
modelBuilder.Entity<BookCategory>()
.HasOne(bc => bc.Book)
.WithMany(b => b.BookCategories)
.HasForeignKey(bc => bc.BookId);
modelBuilder.Entity<BookCategory>()
.HasOne(bc => bc.Category)
.WithMany(c => c.BookCategories)
.HasForeignKey(bc => bc.CategoryId);
如何使其工作? 如何通过odata请求多对多实体?
UPD:
ODATA已配置:
.EntityType.Count().Filter().OrderBy().Expand(SelectExpandType.Allowed,10).Select().Page().Count();
linq查询工作正常:
context.Book.Include(c=>c.BookCategories).ToArray()
答案 0 :(得分:0)
好吧,我的解决方案不是最好的,但是它可行:我们需要向其中添加字段 Id 和唯一约束:
public class BookCategory
{
public int Id { get; set; }
public int BookId { get; set; }
public Book Book { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
和
modelBuilder.Entity<BookCategory>().HasAlternateKey(bc => bc.Id);
,然后,如果要通过odata加载链接的实体,我们还需要将链接实体添加到odata路由。我使用扩展方法,所以它看起来像这样:
public static void RegisterOdataRoute<TEntity>(this ODataConventionModelBuilder builder, string name = null, bool pluralize = true) where TEntity : class
{
name = name ?? $"{typeof(TEntity).Name}";
var names = pluralize ? $"{name}s" : name;
OdataRoutes.Add(name, $"~/odata/{names}");
builder.EntitySet<TEntity>(names).EntityType.Count().Filter().OrderBy().Expand(SelectExpandType.Allowed,10).Select().Page().Count();
}
}
和
app.UseOData(builder =>
{
builder.RegisterOdataRoute<BookCategory>();
...
如果有人找到了更好的解决方案,请告诉我!