Development Tip

코드 우선 vs 모델 / 데이터베이스 우선 [종료]

yourdevel 2020. 10. 2. 23:24
반응형

코드 우선 vs 모델 / 데이터베이스 우선 [종료]


EDMX 다이어그램에서 모델 / 데이터베이스 우선보다 Entity Framework 4.1 코드 우선 사용의 장단점은 무엇입니까?

EF 4.1을 사용하여 데이터 액세스 계층을 구축하는 모든 접근 방식을 완전히 이해하려고합니다. 리포지토리 패턴과 IoC.

코드 우선 접근 방식을 사용할 수 있다는 것을 알고 있습니다. 엔티티와 컨텍스트를 직접 정의 ModelBuilder하고 스키마를 미세 조정하는 데 사용 합니다.

EDMX다이어그램 을 만들고 T4 템플릿을 사용하여 동일한 POCO클래스 를 생성하는 코드 생성 단계를 선택할 수도 있습니다 .

두 경우 모두 불가지론적인 POCO객체 ORM와에서 파생되는 컨텍스트로 끝납니다 DbContext.

Enterprise Manager에서 데이터베이스를 설계하고 모델을 신속하게 동기화하고 디자이너를 사용하여 미세 조정할 수 있기 때문에 Database-first가 가장 매력적으로 보입니다.

그렇다면이 두 접근법의 차이점은 무엇입니까? 선호 VS2010 대 Enterprise Manager에 관한 것입니까?


차이점은 다음과 같습니다.

먼저 코드

  • 하드 코어 프로그래머는 어떤 종류의 디자이너도 좋아하지 않고 EDMX xml에서 매핑을 정의하는 것이 너무 복잡하기 때문에 매우 인기가 있습니다.
  • 코드에 대한 완전한 제어 (수정하기 어려운 자동 생성 코드 없음).
  • 일반적인 기대는 DB에 신경 쓰지 않는 것입니다. DB는 논리가없는 저장소 일뿐입니다. EF는 생성을 처리 할 것이며 사용자는 그것이 어떻게 작동하는지 알고 싶지 않습니다.
  • 코드가 데이터베이스를 정의하기 때문에 데이터베이스에 대한 수동 변경이 손실 될 가능성이 높습니다.

데이터베이스 우선

  • DBA가 설계 한 DB가 있거나 별도로 개발 한 DB가 있거나 기존 DB가있는 경우 매우 인기가 있습니다.
  • EF가 엔터티를 생성하도록 허용하고 매핑을 수정 한 후 POCO 엔터티를 생성합니다.
  • POCO 엔터티에 추가 기능이 필요한 경우 T4 템플릿을 수정하거나 부분 클래스를 사용해야합니다.
  • 데이터베이스가 도메인 모델을 정의하기 때문에 데이터베이스를 수동으로 변경할 수 있습니다. 항상 데이터베이스에서 모델을 업데이트 할 수 있습니다 (이 기능은 매우 잘 작동합니다).
  • 나는 종종 이것을 VS 데이터베이스 프로젝트 (Premium 및 Ultimate 버전 만)와 함께 사용합니다.

먼저 모델

  • IMHO는 디자이너 팬이라면 인기가 있습니다 (= 코드 나 SQL 작성을 좋아하지 않음).
  • 모델을 "그리고"워크 플로가 데이터베이스 스크립트를 생성하고 T4 템플릿이 POCO 엔티티를 생성하도록합니다. 엔터티와 데이터베이스 모두에 대한 제어권의 일부를 잃게되지만 소규모 프로젝트의 경우 매우 생산적입니다.
  • POCO 엔터티에 추가 기능이 필요한 경우 T4 템플릿을 수정하거나 부분 클래스를 사용해야합니다.
  • 모델이 데이터베이스를 정의하기 때문에 데이터베이스에 대한 수동 변경이 손실 될 가능성이 높습니다. 이것은 데이터베이스 생성 파워 팩이 설치된 경우 더 잘 작동합니다. 데이터베이스 스키마를 업데이트하거나 (다시 만드는 대신) VS에서 데이터베이스 프로젝트를 업데이트 할 수 있습니다.

EF 4.1의 경우 Code First 대 모델 / 데이터베이스 우선과 관련된 몇 가지 다른 기능이있을 것으로 예상합니다. Code first에서 사용되는 Fluent API는 EDMX의 모든 기능을 제공하지 않습니다. 저장 프로 시저 매핑, 쿼리 뷰, 뷰 정의 등과 같은 기능은 모델 / 데이터베이스를 먼저 사용할 때 작동하고 DbContext(아직 시도하지 않았 음) 코드에서 먼저 작동하지 않을 것으로 예상합니다 .


"Programming Entity Framework"의 저자 인 Julie Lerman이 작성한이 간단한 "의사 결정 트리"는보다 확신을 가지고 결정을 내리는 데 도움이 될 것이라고 생각합니다.

EF로 다양한 접근 방식을 선택하는 데 도움이되는 의사 결정 트리

자세한 정보는 여기 .


데이터베이스 우선과 모델 우선은 실제 차이가 없습니다. 생성 된 코드는 동일하며이 접근 방식을 결합 할 수 있습니다. 예를 들어, SQL 스크립트를 사용하여 데이터베이스를 변경하고 모델을 업데이트하는 것보다 디자이너를 사용하여 데이터베이스를 만들 수 있습니다.

When you using code first you can't alter model without recreation database and losing all data. IMHO, this limitation is very strict and does not allow to use code first in production. For now it is not truly usable.

Second minor disadvantage of code first is that model builder require privileges on master database. This doesn't affect you if you using SQL Server Compact database or if you control database server.

Advantage of code first is very clean and simple code. You have full control of this code and can easily modify and use it as your view model.

I can recommend to use code first approach when you creating simple standalone application without versioning and using model\database first in projects that requires modification in production.


Quoting the relevant parts from http://www.itworld.com/development/405005/3-reasons-use-code-first-design-entity-framework

3 reasons to use code first design with Entity Framework

1) Less cruft, less bloat

Using an existing database to generate a .edmx model file and the associated code models results in a giant pile of auto generated code. You’re implored never to touch these generated files lest you break something, or your changes get overwritten on the next generation. The context and initializer are jammed together in this mess as well. When you need to add functionality to your generated models, like a calculated read only property, you need to extend the model class. This ends up being a requirement for almost every model and you end up with an extension for everything.

With code first your hand coded models become your database. The exact files that you’re building are what generate the database design. There are no additional files and there is no need to create a class extension when you want to add properties or whatever else that the database doesn't need to know about. You can just add them into the same class as long as you follow the proper syntax. Heck, you can even generate a Model.edmx file to visualize your code if you want.

2) Greater Control

When you go DB first, you’re at the mercy of what gets generated for your models for use in your application. Occasionally the naming convention is undesirable. Sometimes the relationships and associations aren't quite what you want. Other times non transient relationships with lazy loading wreak havoc on your API responses.

While there is almost always a solution for model generation problems you might run into, going code first gives you complete and fine grained control from the get go. You can control every aspect of both your code models and your database design from the comfort of your business object. You can precisely specify relationships, constraints, and associations. You can simultaneously set property character limits and database column sizes. You can specify which related collections are to be eager loaded, or not be serialized at all. In short, you are responsible for more stuff but you’re in full control of your app design.

3)Database Version Control

This is a big one. Versioning databases is hard, but with code first and code first migrations, it’s much more effective. Because your database schema is fully based on your code models, by version controlling your source code you're helping to version your database. You’re responsible for controlling your context initialization which can help you do things like seed fixed business data. You’re also responsible for creating code first migrations.

When you first enable migrations, a configuration class and an initial migration are generated. The initial migration is your current schema or your baseline v1.0. From that point on you will add migrations which are timestamped and labeled with a descriptor to help with ordering of versions. When you call add-migration from the package manager, a new migration file will be generated containing everything that has changed in your code model automatically in both an UP() and DOWN() function. The UP function applies the changes to the database, the DOWN function removes those same changes in the event you want to rollback. What’s more, you can edit these migration files to add additional changes such as new views, indexes, stored procedures, and whatever else. They will become a true versioning system for your database schema.


Code-first appears to be the rising star. I had a quick look at Ruby on Rails, and their standard is code-first, with database migrations.

If you are building an MVC3 application, I believe Code first has the following advantages:

  • Easy attribute decoration - You can decorate fields with validation, require, etc.. attributes, it's quite awkward with EF modelling
  • No weird modelling errors - EF modelling often has weird errors, such as when you try to rename an association property, it needs to match the underlying meta-data - very inflexible.
  • Not awkward to merge - When using code version control tools such as mercurial, merging .edmx files is a pain. You're a programmer used to C#, and there you are merging a .edmx. Not so with code-first.
  • Contrast back to Code first and you have complete control without all the hidden complexities and unknowns to deal with.
  • I recommend you use the Package Manager command line tool, don't even use the graphical tools to add a new controller to scaffold views.
  • DB-Migrations - Then you can also Enable-Migrations. This is so powerful. You make changes to your model in code, and then the framework can keep track of schema changes, so you can seamlessly deploy upgrades, with schema versions automatically upgraded (and downgraded if required). (Not sure, but this probably does work with model-first too)

Update

The question also asks for a comparison of code-first to EDMX model/db-first. Code-first can be used for both of these approaches too:


I use EF database first in order to provide more flexibility and control over the database configuration.

EF code first and model first seemed cool at first, and provides database independence, however in doing this it does not allow you to specify what I consider very basic and common database configuration information. For example table indexes, security metadata, or have a primary key containing more than one column. I find I want to use these and other common database features and therefore have to do some database configuration directly anyway.

I find the default POCO classes generated during DB first are very clean, however lack the very useful data annotation attributes, or mappings to stored procedures. I used the T4 templates to overcome some of these limitations. T4 templates are awesome, especially when combined with your own metadata and partial classes.

Model first seems to have lots of potential, but is giving me lots of bugs during complex database schema refactoring. Not sure why.


Working with large models were very slow before the SP1, (have not tried it after the SP1, but it is said that is a snap now).

I still Design my tables first, then an in-house built tool generates the POCOs for me, so it takes the burden of doing repetitive tasks for each poco object.

when you are using source control systems, you can easily follow the history of your POCOs, it is not that easy with designer generated code.

I have a base for my POCO, which makes a lot of things quite easy.

I have views for all of my tables, each base view brings basic info for my foreign keys and my view POCOs derive from my POCO classes, which is quite usefull again.

And finally I dont like designers.


Database first approach example:

Without writing any code: ASP.NET MVC / MVC3 Database First Approach / Database first

And I think it is better than other approaches because data loss is less with this approach.


IMHO I think that all the models have a great place but the problem I have with the model first approach is in many large businesses with DBA's controlling the databases you do not get the flexibility of building applications without using database first approaches. I have worked on many projects and when it came to deployment they wanted full control.

따라서 가능한 모든 변형에 동의하는 한 Code First, Model First, Database 먼저 실제 프로덕션 환경을 고려해야합니다. 따라서 시스템이 많은 사용자와 DBA가 쇼를 실행하는 대규모 사용자 기반 응용 프로그램이 될 경우 데이터베이스 우선 옵션을 제 생각에 고려할 수 있습니다.


먼저 코드의 장점 중 하나는 Git과 같은 버전 제어 시스템에 대한 모든 변경 사항을 백업 할 수 있다는 것입니다. 모든 테이블과 관계가 본질적으로 클래스에 저장되기 때문에 시간을 거슬러 올라가 데이터베이스의 구조가 이전에 무엇인지 확인할 수 있습니다.

참고 URL : https://stackoverflow.com/questions/5446316/code-first-vs-model-database-first

반응형