我是.NET Core的新手,请原谅我,如果这个问题不适合Stackoverdlow。我正在使用带有.NET Core 2.1的CosmosDB。我有一个简单的课程,我坚持下面的集合。
public class Customer
{
public string Id { get; private set; }
public string FirstName { get; private set; }
public string LastName { get; private set; }
public Customer(string firstName, string lastName) {
if (string.IsNullOrWhiteSpace(firstName) || string.IsNullOrWhiteSpace(lastName))
{
throw new ArgumentException("First and Last name are required");
}
this.FirstName = firstName;
this.LastName = lastName;
}
}
注意私有集,因为Id是由数据库自动生成的,并且永远不应由调用者设置。
当我保存记录并检索它们时,不会填充Id属性。但是,如果我将setter更改为public,它就可以了。这是一个非常简单的例子,但理想情况下我应该能够将Id setter设为私有,因为它应该在类外部是不可变的。我过去在Java中使用了像Hibernate这样的库,因为这个字段是通过反射设置的。
.NET Core和CosmosDB有没有办法处理私有设置器?在尝试实现OOP / DDD方法时,我可以看到这会在像Order这样的域上出现问题。
public class Order
{
public int Id { get; private set; }
public IList<LineItem> LineItems { get; private set; }
public void AddLineItem(LineItem lineItem) {
// do some business logic, encapsulatng the line items
// IE don't just let the caller have free reign
}
}
public class LineItem
{
public string SKU { get; set; }
public int Qty { get; set; }
public decimal PricePerUnit { get; set; }
}
由于CosmosDb具有预定义的属性id
,因此需要JSON序列化程序绑定到它,并且由于这是区分大小写的,因此这是允许您执行此操作的属性:
public class Customer
{
[JsonProperty("id")]
public string Id { get; private set; }
// other members
}
就个人而言,我更喜欢添加另一个属性来存储任何未映射的属性
/// <summary>
/// Any unmapped properties from the JSON data deserializes into this property.
/// </summary>
[JsonExtensionData]
public IDictionary<string, JToken> UnmappedData { get; set; }
因此,至少在调试时我会发现由于区分大小写,拼写错误等而可能遗漏的任何属性。
实际上,我对CosmosDb模型的Base类看起来像:
/// <summary>
/// Implements auto generated Id property for CosmosDb Model
/// </summary>
public abstract class BaseModel
{
/// <summary>
/// PK for this model. (apart from the ResourceId which is internally generated by CosmoDb)
/// If the user does not set this, the SDK will set this automatically to a GUID.
/// </summary>
[JsonProperty(PropertyName = "id")]
public virtual string Id { get; set; }
/// <summary>
/// Any unmapped properties from the JSON data deserializes into this property.
/// </summary>
[JsonExtensionData]
public IDictionary<string, JToken> UnmappedData { get; set; }
}