C# 将导航属性添加到普通对象
因此,我的应用程序中有一个viewmodel,看起来像:C# 将导航属性添加到普通对象,c#,entity-framework,asp.net-web-api,C#,Entity Framework,Asp.net Web Api,因此,我的应用程序中有一个viewmodel,看起来像: public class CountryVM { [Key] public int CountryID { get; set; } [ForeignKey("Country_CountryID")] public virtual ICollection<OrganisationVM> Organisations { get; set; }
public class CountryVM
{
[Key]
public int CountryID { get; set; }
[ForeignKey("Country_CountryID")]
public virtual ICollection<OrganisationVM> Organisations { get; set; }
public CountryVM(Country country)
{
if (country == null) return;
this.CountryID = country.CountryID;
}
}
现在,Organization和Country是我数据库中的表,OrganizationVM是一个视图。CountryVM仅存在于应用程序中,此时EF试图在我的数据库“dbo.CountryVMs”中创建一个表
有没有办法像这样连接它,这样我就可以在CountryVM中使用导航属性,而不用创建表
我想这样做的原因是:
目前我的web.api控制器中有以下代码:
// GET: odata/Country
[EnableQuery]
public IQueryable<CountryVM> Get()
{
var a = db.Countries.ToList().Select<Country, CountryVM>(c => new CountryVM(c)).AsQueryable();
return a;
}
我希望odata允许我使用expand和select来选择countryVMs组织,但到目前为止还没有。它不会扩展,因为CountryVM构造函数只分配CountryID,而不是导航集合,因此为空。如果在DbContext中启用了延迟加载,则只要将集合从一个国家移动到另一个国家,延迟加载就应该可以工作。另外,调用ToList将有效地实现Select之前表中的所有条目,请记住这一点。
public class Organisation
{
[Key]
public int OrganisationId { get; set; }
[Required]
public virtual Country Country { get; set; }
}
public class OrganisationVM
{
[Key]
public int OrganisationId { get; set; }
[ForeignKey("Country_CountryID")]
public virtual CountryVM Country { get; set; }
public int? Country_CountryID { get; set; }
}
// GET: odata/Country
[EnableQuery]
public IQueryable<CountryVM> Get()
{
var a = db.Countries.ToList().Select<Country, CountryVM>(c => new CountryVM(c)).AsQueryable();
return a;
}