更新时间:2022-12-24 19:00:33
我尝试对您提到的每一点做一个简短的回答
I try to give a short answer to each point you mentioned
partial
类对于工具生成的代码特别有用.假设您要实现仅模型的派生属性.对于第一个代码,您可以随时随地进行操作.对于数据库优先,如果您更新模型,则将重写类文件.因此,如果要保留扩展代码,则要将其放置在托管模型之外的其他文件中-这是partial
帮助您扩展类的地方,而无需手动调整自动生成的代码.
partial
classes are specially useful for tool-generated code. Suppose you want to implement a model-only derived property. For code first, you would just do it, wherever you want. For database first, the class file will be re-written if you update your model. So if you want to keep your extension code, you want to place it in a different file outside the managed model - this is where partial
helps you to extend the class without tweaking the auto-generated code by hand.
ICollection
绝对是一个合适的选择,即使对于代码优先.如果没有排序语句,您的数据库可能将始终不支持定义的顺序.
ICollection
is definitely a suitable choice, even for code first. Your database probably won't support a defined order anyway without a sorting statement.
构造函数初始化至少很方便...假设您有一个空的数据库收集集合,或者根本没有加载该属性.如果没有构造函数,则必须在代码中的任意点显式处理null
情况.我现在无法回答是选择List
还是HashSet
.
Constructor initialization is a convenience at least... suppose you have either an empty collection database-wise or you didn't load the property at all. Without the constructor you have to handle null
cases explicitely at arbitrary points in code. Whether you should go with List
or HashSet
is something I can't answer right now.
virtual
启用数据库实体的代理创建,这可以帮助两件事:如前所述,延迟加载和更改跟踪.代理对象可以使用设置器立即跟踪对虚拟属性的更改,而上下文中的普通对象需要在SaveChanges
上进行检查.在某些情况下,这可能会更有效(并非通常如此).
virtual
enables proxy creation for the database entities, which can help with two things: Lazy Loading as you already mentioned and change tracking. A proxy object can track changes to virtual properties immediately with the setter, while normal objects in the context need to be inspected on SaveChanges
. In some cases, this might be more efficient (not generally).
virtual IDbSet
上下文条目使单元测试的测试模型上下文更容易设计.其他用例也可能存在.
virtual IDbSet
context entries allow easier design of testing-mockup contexts for unit tests. Other use cases might also exist.