我将 web api 2.2 用于 odata v4,以下是模型:
[Table("User")]
public partial class User
{
public User()
{
UserRoles = new HashSet<UserRole>();
}
[StringLength(50)]
public string Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
public virtual ICollection<UserRole> UserRoles { get; set; }
}
[Table("UserRole")]
public partial class UserRole
{
[Key]
[Column(Order = 0)]
[StringLength(50)]
public string UserId { get; set; }
[Key]
[Column(Order = 1)]
[StringLength(50)]
public string RoleName { get; set; }
public virtual User User { get; set; }
}
以下是 WebApiConfig.cs 代码:
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<User>("Users");
builder.EntitySet<UserRole>("UserRoles");
config.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());
config.AddODataQueryFilter();
到现在为止,每件事都运作良好。但是,如果我从 UserRole 定义中删除 [Key]。并使用代码:
builder.EntitySet<UserRole>("UserRoles").EntityType.HasKey(r => new { r.UserId, r.RoleName });
当我查询用户时,我总是得到告诉用户角色没有键定义的错误。
我已经上传了源 porject 文件@https ://cloud.seafile.com/f/bdff340ec3/ 请检查 webapiconfig.cs User.cs UserRole.cs 和 web.config(用于数据库连接字符串)。当你访问 /odata/Users?$expand=UserRoles 你会得到错误