C#-ASP.Net Core Web API-ICollection没有显示在JSON结果集中
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#-ASP.Net Core Web API-ICollection没有显示在JSON结果集中,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含8564字,纯文字阅读大概需要13分钟。
内容图文
![C#-ASP.Net Core Web API-ICollection没有显示在JSON结果集中](/upload/InfoBanner/zyjiaocheng/687/2e8fd6ecdcea426cb24ed8e7d2fdd9ef.jpg)
我正在尝试执行3个proc,以构建客户对象并将其返回给客户端.但是,在我的api(服务器端)内部,我可以正确看到结果.但是,不幸的是,结果集中(客户端)缺少ICollection数据
我正在使用Entity Framework和OData
所以,这是我的模型:
public class Customer
{
[Key]
public Guid Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string VatCode { get; set; }
public string ChamberOfCommerceCode { get; set; }
public DateTime Modified { get; set; }
public DateTime Created { get; set; }
public string LanguageCode { get; set; }
public decimal Discount { get; set; }
public string CustomerManager { get; set; }
public Guid PriceList { get; set; }
public Guid PaymentCondition { get; set; }
// public bool VatLiable { get; set; }
public bool IsBlocked { get; set; }
public bool IsProspect { get; set; }
public bool IsSuspect { get; set; }
public string Website { get; set; }
public string DashboardUrl { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public ICollection<FreeFields> FreeFields { get; set; }
// [NotMapped]
// public Dictionary<string, string> UknownElements { get; set; }
[ForeignKey(nameof(Contacts.Customer))]
public ICollection<Contacts> Contact { get; set; }
[ForeignKey(nameof(Addresses.Customer))]
public ICollection<Addresses> Address { get; set; }
}
如您所见,我们在那里有2个ICollection:联系人和地址.
这里是这两个的模型:
联系人模型
public class Contacts
{
[Key]
public Guid Id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Initials { get; set; }
public string Function { get; set; }
[Column("Customer")]
public Guid Customer { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public string LanguageCode { get; set; }
public bool IsMainContact { get; set; }
public string Gender { get; set; }
public string Username { get; set; }
}
和地址
public class Addresses
{
[Key]
public Guid Id { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string PostalCode { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string CountryCode { get; set; }
public string Type { get; set; }
[Column("Customer")]
public Guid Customer { get; set; }// This Property should be GUID instead of String..
public bool IsMainAddress { get; set; }
public string Route { get; set; }
public string State { get; set; }
}
现在,在我的控制器内部,我从存储过程中获取数据并创建模型:
public IList<Customer> GetAllCustomers()
{
//Initialize the objects
IList<Customer> customers = null;
ICollection<Contacts> contacts = null;
ICollection<Addresses> addresses = null;
Dictionary<string, string> thisdict = null;
//Fetch the data from stored procedures
customers = db.Customers.FromSql("SIP_API_MONDIA_Customers_sel").ToList();
contacts = db.Contacts.FromSql("SIP_API_MONDIA_Contacts_sel").ToList();
addresses = db.Addresses.FromSql("SIP_API_MONDIA_Address_sel").ToList();
//Loop through customers and add the contact and addresses when required
foreach(var item in customers)
{
item.Contact = contacts.Where(x => x.Customer == item.Id).ToList();
item.Address = addresses.Where(x => x.Customer == item.Id).ToList();
// item.UknownElements = thisdict;
}
return customers;
}
Tihs正常工作,我可以在断点处看到客户对象已填充.地址和联系人也正确.但是,一旦我将其返回给客户端,结果将丢失两个ICollections.
我觉得我缺少一个小细节,但找不到.
解决方法:
因此,首先,如果遵循命名约定,则无需显式使用属性.可以安全删除键属性.如果将属性名称更改为复数名称,则可以删除ForeignKey属性:“联系人”和“地址”.我强烈建议您对类使用单数名称,对集合导航属性使用复数名称(例如,一对多关系).
// Contact is name of class, plural name for property: Contacts
public ICollection<Contact> Contacts { get; set; }
如果您使用的是OData,则应构建EDM model(但没有显示给我们).如果可以访问DbContext,也不要对简单的SELECT使用存储过程.
您的整个控制器逻辑都是不必要的,可以替换为:
[EnableQuery]
public IQueryable<Customer> GetAllCustomers()
{
return db.Customers;
}
因此,在代码中它看起来像:
客户等级
public class Customer
{
public Guid Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string VatCode { get; set; }
public string ChamberOfCommerceCode { get; set; }
public DateTime Modified { get; set; }
public DateTime Created { get; set; }
public string LanguageCode { get; set; }
public decimal Discount { get; set; }
public string CustomerManager { get; set; }
public Guid PriceList { get; set; }
public Guid PaymentCondition { get; set; }
public bool IsBlocked { get; set; }
public bool IsProspect { get; set; }
public bool IsSuspect { get; set; }
public string Website { get; set; }
public string DashboardUrl { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public ICollection<FreeFields> FreeFields { get; set; }
public ICollection<Contact> Contacts { get; set; }
public ICollection<Address> Addresses { get; set; }
}
接触类
public class Contact
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Initials { get; set; }
public string Function { get; set; }
public Guid Customer { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public string LanguageCode { get; set; }
public bool IsMainContact { get; set; }
public string Gender { get; set; }
public string Username { get; set; }
public Guid CustomerId { get; set; }
// If you want to use class reference navigation property (also called as "hard reference").
// That can be used in "$expand" or "$select" for example.
// Uncomment the following line:
// public Customer Customer { get; set }
}
地址类别
public class Address
{
public Guid Id { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string PostalCode { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string CountryCode { get; set; }
public string Type { get; set; }
public bool IsMainAddress { get; set; }
public string Route { get; set; }
public string State { get; set; }
public Guid CustomerId { get; set; }
// If you want to use class reference navigation property (also called as "hard reference").
// That can be used in "$expand" or "$select" for example.
// Uncomment the following line:
// public Customer Customer { get; set }
}
建立您的EDM模型:
public class MyModelBuilder
{
public IEdmModel GetEdmModel(IServiceProvider serviceProvider)
{
var builder = new ODataConventionModelBuilder(serviceProvider);
builder.EntitySet<Address>("Addresses")
.EntityType
.Filter() // Allow for the $filter Command
.Count() // Allow for the $count Command
.Expand() // Allow for the $expand Command
.OrderBy() // Allow for the $orderby Command
.Page() // Allow for the $top and $skip Commands
.Select();// Allow for the $select Command;
builder.EntitySet<Contact>("Contacts")
.EntityType
.Filter() // Allow for the $filter Command
.Count() // Allow for the $count Command
.Expand() // Allow for the $expand Command
.OrderBy() // Allow for the $orderby Command
.Page() // Allow for the $top and $skip Commands
.Select() // Allow for the $select Command
.Expand();
builder.EntitySet<Customer>("Customers")
.EntityType
.Filter() // Allow for the $filter Command
.Count() // Allow for the $count Command
.Expand() // Allow for the $expand Command
.OrderBy() // Allow for the $orderby Command
.Page() // Allow for the $top and $skip Commands
.Select() // Allow for the $select Command
.Expand();
return builder.GetEdmModel();
}
}
在启动中使用它:
public void ConfigureServices(IServiceCollection services)
{
// ... Other Configurations
services.AddOData();
services.AddTransient<MyModelBuilder>();
// ... MVC Service Configurations
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, MyModelBuilder modelBuilder)
{
// ... Other Configurations
app.UseMvc(routeBuilder =>
{
routeBuilder.MapODataServiceRoute("ODataRoutes", "odata", modelBuilder.GetEdmModel(app.ApplicationServices));
});
}
最后创建控制器:
[Produces("application/json")]
public class CustomersController : ODataController
{
private readonly MyDbContext _context;
public CustomersController (MyDbContext context) => _context = context;
[EnableQuery]
public IQueryable<Customer> GetAllCustomers() => _context.Customers;
}
(在上面的代码中,我假设您已经正确配置了DbContext)
现在,您应该可以使用$expand或$select获取例如所有客户地址.
HTTP GET /odata/Customers?$expand=Addresses
内容总结
以上是互联网集市为您收集整理的C#-ASP.Net Core Web API-ICollection没有显示在JSON结果集中全部内容,希望文章能够帮你解决C#-ASP.Net Core Web API-ICollection没有显示在JSON结果集中所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。