我进行了很多搜索,我认为这是可能的,但是我感觉好像只是被阻止知道如何正确格式化它。
我有一个代表产品的类,它是从CRM到Magento的关系类。
在构造函数中,我必须做一些类似的事情...
public Product(IBaseProduct netforumProduct, MagentoClient client)
{
Product existingMagentoProduct = client.GetProductBySku(netforumProduct.Code);
if (existingMagentoProduct != null)
{
this.id = existingMagentoProduct.id;
this.name = existingMagentoProduct.name;
... many of them ...
this.visibility = existingMagentoProduct.visibility;
this.extension_attributes.configurable_product_links = existingMagentoProduct.extension_attributes.configurable_product_links;
}
else
{
// its a new product, new up the objects
this.id = -1;
this.product_links = new List<ProductLink>();
this.options = new List<Option>();
this.custom_attributes = new List<CustomAttribute>();
this.media_gallery_entries = new List<MediaGalleryEntry>();
this.extension_attributes = new ExtensionAttributes();
this.status = 0; // Keep all new products disabled so they can be added to the site and released on a specific day (this is a feature, not an issue / problem).
this.attribute_set_id = netforumProduct.AttributeSetId;
this.visibility = 0;
}
}
不得不像这样初始化所有属性似乎很愚蠢。我可以使用一个映射器,但这似乎是一个创可贴。我必须先查看该产品是否存在于magento中,并填充其ID和值,否则每当我保存产品时,它都会创建一个附加产品。
我考虑过做类构造函数来调用静态方法,但语法不正确。
可能为时已晚,我需要一段时间考虑其他事情。
如果必须在构造函数中执行此操作,则可以通过先将'default'值设置为'Product'属性来摆脱很多代码。这将消除在构造函数中执行这些操作的需要。接下来,如果要自动设置类的属性,则可以使用反射。
public class Product
{
public int Id { get; set; } = -1;
public List<ProductLink> Product_Links { get; set; } = new List<ProductLink>();
....
public int Visibility { get; set; } = 0;
public Product(IBaseProduct netforumProduct, MagentoClient client)
{
var existingMagentoProduct = client.GetProductBySku(netforumProduct.Code);
if (existingMagentoProduct != null)
{
foreach (PropertyInfo property in typeof(Product).GetProperties().Where(p => p.CanWrite))
{
property.SetValue(this, property.GetValue(existingMagentoProduct, null), null);
}
}
}
}
尽管,我想指出您可能不应该在类构造函数中使用REST客户端,尤其是仅填充其数据(同时,您正在执行同步操作)。拥有另一个负责使用客户端填充此类的层,然后使用诸如AutoMapper之类的数据将其映射到它上,这样会更清洁。