What is a proper way of writing entity POCO classes in Entity Framework Core?

前端 未结 1 557
轻奢々
轻奢々 2021-02-20 12:13

EF Core has a \"code first mentality\" by default, i.e. it is supposed to be used in a code-first manner, and even though database-first approach is supported, it is described a

1条回答
  •  感动是毒
    2021-02-20 13:08

    I try to give a short answer to each point you mentioned

    • 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 is definitely a suitable choice, even for code first. Your database probably won't support a defined order anyway without a sorting statement.

    • 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 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 context entries allow easier design of testing-mockup contexts for unit tests. Other use cases might also exist.

    0 讨论(0)
提交回复
热议问题