C#映射两个复杂的对象 [英] C# map two complex objects
问题描述
我有四节课:
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Product> Product { get; set; }
}
public class Product
{
public int ProductNumber { get; set; }
public string ProductColor { get; set; }
}
///////////////////////////////////////////////
public class Customer_
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Article> Article { get; set; }
}
public class Article
{
public int ArticleNumber { get; set; }
public string ArticleColor { get; set; }
}
还有一个实例:
var Cus = new List<Customer>
{
new Customer()
{
FirstName = "FirstName1",
LastName = "LastName1",
Product = new List<Product>
{
new Product()
{
ProductColor = "ProductColor1",
ProductNumber = 11
}
}
},
new Customer()
{
FirstName = "FirstName2",
LastName = "LastName2",
Product = new List<Product>
{
new Product()
{
ProductColor = "ProductColor2",
ProductNumber = 12
}
}
}
};
我想用实例 Cus
的值创建一个新对象 List< Customer_>
.例如 Customer.FirstName = Customer_.FirstName,Customer.Product.ProductColor = Customer_.Article.ArticleColor等
I want to create a new object List<Customer_>
with the value of my instance Cus
. For example Customer.FirstName = Customer_.FirstName, Customer.Product.ProductColor = Customer_.Article.ArticleColor etc
轻松实现此目的的最佳方法是什么?有人可以使用 Dictionary
吗?
What is the best way to do this easily, could one use a Dictionary
?
推荐答案
Mapping can be accomplished through the use of an Interface
.
定义一个或多个接口,这些接口提供逻辑上命名的属性(例如您提到的常见颜色属性)的映射:
Define an interface(s) which provide a mapping of logically named properties such as the common color properties you mention:
// Some entities have different named properties but can be joined
// using those properties. This interface shows a common color which
// when implemented will route the processing to a common shared property
// which reports and sets the associated color.
public interface IDefinedColor
{
string Color { get; set; }
}
如果您必须为 Product
和 Article
创建 partial
类,并使它们遵守上述接口.提示,如果使用诸如EF之类的实体映射器,这是使用partials进行这种映射的好方法.实现实现接口并连接通用性:
If you have to create partial
classes for Product
and Article
and have them adhere to said interfaces. Hint if using an entity mapper such as EF this is a great way to do such maping using partials. Implement implement the interface and hook up the commonality:
// Holds the common properties for future processing.
public partial class Product : IDefinedColor
{
public string Color
{
get { return ProductColor; }
set { ProductColor = value; }
}
}
然后根据需要从 IDefinedColor
映射实现中解决问题.
Then work off of the IDefinedColor
mapped implementations as needed.
通过使用接口,一个方法是让所有未来的开发人员都知道该合同,该合同在属性中指定了业务逻辑相等性,并且未隐藏在其他 joining 类中.
By using interfaces one is letting all future developers know of the contract which specifies a business logic equality in the properties and it is not hidden in other joining classes.
这篇关于C#映射两个复杂的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!