gpt4 book ai didi

c# - 存储库应该使用对象还是原语?

转载 作者:行者123 更新时间:2023-11-30 20:07:57 33 4
gpt4 key购买 nike

我注意到,对于我的存储库是将对象还是基元作为参数,或者 CREATE 方法是否只返回一个 int(来自数据库的 ID)或完整的对象,真的没有任何规律或理由。

所以我的问题是,存储库应该传递并返回对象还是原语?在这个问题上你有什么建议?您能否分享这两种方法的任何陷阱或经验?

例子:

public class ProductRepository : IProductRepository
{
// Pass in the whole object to the repo method...?
public int Add(Product product)
{
// return just the productId...?
}

// Pass in the individual primitive values...?
public Product Add(string productName, decimal productPrice, string description)
{
// return the whole Product object...?
}
}

如果需要来自多个对象的信息怎么办?当然,从 OOP 的角度来看,最好在这里传递对象,不是吗? (我在这里很厚颜无耻...)

public int Add(int merchantId, Product product)
{
// database call needs merchant info...
}

public int Add(Merchant merchant, Product product)
{
var merchantId = merchant.ID;
// database call needs merchant info...
}

最佳答案

通常您会在短时间后(如果您使用多个存储库)看到这本身就是一种模式,并且可以在某种基类中重构(用于数据访问)。但是为了做到这一点,您将无法为添加/更新等提供扩展参数(您也不应该 - 只考虑具有 10 多个属性的对象),而只能提供对象本身的模式。

所以使用选项 1 ;)

关于c# - 存储库应该使用对象还是原语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7718062/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com