如何在另一个模型类中获取领域类的列表数据?
1. Directly add a list property to your model class
If the list is meant to be part of your model's state (like for passing data between layers or to a view), the simplest approach is to declare a property of type List<DomainClassExample> directly in your model:
public class YourOtherModelClass { // Add any other properties your model needs public string ModelName { get; set; } // The list of DomainClassExample instances public List<DomainClassExample> DomainItems { get; set; } = new List<DomainClassExample>(); }
You can then populate this list wherever you need to use the model (e.g., in a controller, service, or factory):
// Example of initializing and populating the model var myModel = new YourOtherModelClass(); myModel.DomainItems.Add(new DomainClassExample { ClientAssessmentId = 1, IfaId = 100 }); myModel.DomainItems.Add(new DomainClassExample { ClientAssessmentId = 2, IfaId = 101 });
2. Use a service/repository for data-driven scenarios
If your list comes from a database, API, or external data source, it’s best to abstract the data retrieval into a service or repository. This keeps your model clean and follows the separation of concerns principle.
First, create a service interface and implementation to handle data fetching:
public interface IDomainDataService { List<DomainClassExample> GetDomainItems(); } public class DomainDataService : IDomainDataService { public List<DomainClassExample> GetDomainItems() { // Replace this with your actual data retrieval logic (EF Core query, API call, etc.) return new List<DomainClassExample> { new DomainClassExample { ClientAssessmentId = 1, IfaId = 100 }, new DomainClassExample { ClientAssessmentId = 2, IfaId = 101 } }; } }
Then, inject this service into your model (or into a class that uses your model, like a controller) to populate the list:
// Using dependency injection (common in ASP.NET Core apps) public class YourOtherModelClass { public List<DomainClassExample> DomainItems { get; private set; } // Constructor injection to get the service public YourOtherModelClass(IDomainDataService dataService) { DomainItems = dataService.GetDomainItems(); } }
3. Populate the list via a method (for lazy loading or control)
If you want more control over when the list is loaded (e.g., lazy loading), you can add a method to your model that initializes or fetches the list on demand:
public class YourOtherModelClass { private List<DomainClassExample> _domainItems; public List<DomainClassExample> GetDomainItems() { if (_domainItems == null) { // Initialize or fetch the list here _domainItems = new List<DomainClassExample> { new DomainClassExample { ClientAssessmentId = 1, IfaId = 100 } }; } return _domainItems; } }
Choose the approach that fits your use case: the first is perfect for simple data transfer, the second works best for enterprise apps with external data sources, and the third gives you fine-grained control over loading behavior.
内容的提问来源于stack exchange,提问作者StarLord

