gpt4 book ai didi

servicestack - 使用 ServiceStack.OrmLite 填充 POCO

转载 作者:行者123 更新时间:2023-12-04 04:45:12 25 4
gpt4 key购买 nike

考虑以下领域模型:

class Customer
{
int id {get;set}
string Name {get;set}
List<Contact> Contacts {get;set}
}

class Contact
{
int id {get;set}
string FullName {get;set}
List<PhoneNumber> {get;set}
}

class PhoneNumber
{
int id {get;set}
PhoneType Type {get;set}
string Number {get;set}
}

客户、联系人和电话号码在我们的数据库中是独立的实体。

关于如何使用 ORMLite 和/或 Dapper 以最有效的方式使用其所有链接联系人和联系人电话号码填充完整客户的任何建议,同时考虑调用 db 和 cpu 周期以映射到 POCO ?

最佳答案

如果您使用的是 ORMLite,那么它有一个名为 [Ignore] 的属性,您可以将其放置在您的属性上,这意味着它们不会被持久化(我发现这对于导航很有用我模型上的属性)

因此,我将执行以下操作:

public class Customer : IHasIntId
{
[AutoIncrement]
[PrimaryKey]
public int Id {get;set}
public string Name {get;set}
[Ignore]
public List<Contact> Contacts {get;set}
}

public class Contact : IHasIntId
{
[AutoIncrement]
[PrimaryKey]
public int Id {get;set}
public string FullName {get;set}

[References(typeof(Customer)]
public int CustomerId {get;set;}

[Ignore]
public List<PhoneNumber> PhoneNumbers {get;set}
}

public class PhoneNumber : IHasIntId
{
[AutoIncrement]
[PrimaryKey]
public int id {get;set}
public PhoneType Type {get;set}
public string Number {get;set}

[References(typeof(Contact))]
public int ContactId {get;set;}
}

然后在您的 CustomersService 中,这样的内容就足够了:

public class CustomersService : Service {
public object Get(Customers request) {
var customers = Db.Select<Customer>();
var customerIds = customers.Select(c=>c.Id).ToList();
var contacts = Db.Select<Contact>(c=>customerIds.Contains(c.CustomerId));
var contactIds = contacts.Select(c=>c.Id).ToList();
var phoneNumbers = Db.Select<PhoneNumber>(p=>contactIds.Contains(p.ContactId));

customers.ForEach(customer=> {
var customerContacts = contacts.Where(c=>c.CustomerId == customer.Id);
customerContacts.ForEach(contact=> {
contact.PhoneNumbers = phoneNumbers.Where(p=>p.ContactId ==
contact.Id).ToList();
});

customer.Contacts = customerContacts
});

return new CustomersResponse {
Result = customers
}
}
}

注意:我使用的是 ServiceStack ORMLite 版本 3.*。我知道在 v4 中有更好的方法,请在此处查看:https://github.com/ServiceStack/ServiceStack.OrmLite/blob/master/tests/ServiceStack.OrmLite.Tests/LoadReferencesTests.cs#L80

关于servicestack - 使用 ServiceStack.OrmLite 填充 POCO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20563669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com