假设我有以下我希望不可变的 C# 类。您只能使用参数化构造函数来设置它。
public class InsulineInjection
{
private InsulineInjection()
{
// We don't want to enable a default constructor.
}
public InsulineInjection(Millilitre millilitre, DateTime dateTime, string remark)
{
this.Remark = remark;
this.DateTime = dateTime;
this.Millilitre = millilitre;
}
public string Remark { get; private set; }
public DateTime DateTime { get; private set; }
public Millilitre Millilitre { get; private set; }
}
现在我想使用 ORM 来创建这个 POCO。然而,据我所知,所有 .NET ORM 都希望属性可以访问,并且有一个公共(public)构造函数来创建这个 POCO。所以我必须将我的 POCO 更改为:
public class InsulineInjection
{
public InsulineInjection()
{
}
public InsulineInjection(Millilitre millilitre, DateTime dateTime, string remark)
{
this.Remark = remark;
this.DateTime = dateTime;
this.Millilitre = millilitre;
}
public string Remark { get; set; }
public DateTime DateTime { get; set; }
public Millilitre Millilitre { get; set; }
}
然而,这使我的 POCO 再次可变。使用它的人之后可以简单地更改任何我不想要的属性。
据我所知,我可以通过两种不同的方式解决这个问题:
- 编写我自己的数据访问层(或修改 orm),以便能够使用我创建的构造函数创建正确的 POCO 实例。
- 创建某种映射器。让 ORM 创建简单的 DTO 对象,并在适当的时候使用映射器将 DTO 对象转换为我的 POCO。
我倾向于解决方案 2。有人有关于如何执行此操作的示例吗?或者有人有比我上面描述的更好的解决方案吗?
最佳答案
许多 OR/M 只要有一个默认的构造函数和 setter 就可以工作(不管它们是否公开,它们只需要存在)
所以这行不通(没有默认构造函数):
public class InsulineInjection
{
public InsulineInjection(Millilitre millilitre, DateTime dateTime, string remark)
{
this.Remark = remark;
this.DateTime = dateTime;
_millilitre = millilitre;
}
public string Remark { get; set; }
public DateTime DateTime { get; set; }
public Millilitre Millilitre { get { return _millilitre; } }
}
或这个(最后一个属性没有二传手)
public class InsulineInjection
{
public InsulineInjection(Millilitre millilitre, DateTime dateTime, string remark)
{
this.Remark = remark;
this.DateTime = dateTime;
_millilitre = millilitre;
}
public string Remark { get; set; }
public DateTime DateTime { get; set; }
public Millilitre Millilitre { get { return _millilitre; } }
}
虽然这会起作用:
public class InsulineInjection
{
protected InsulineInjection()
{
// works with many OR/Ms
}
public InsulineInjection(Millilitre millilitre, DateTime dateTime, string remark)
{
this.Remark = remark;
this.DateTime = dateTime;
this.Millilitre = millilitre;
}
public string Remark { get; private set; }
public DateTime DateTime { get; private set; }
public Millilitre Millilitre { get; private set; }
}
关于c# - POCO、ORM 和不变性。如何让它们协同工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13309925/