Отличие ado net от entity framework
Как работать с EF в многоуровневом приложении?
Например, у нас есть какой-то DAL с EF. Я видел много статей и проектов, в которых репозиторий, шаблоны единиц работы использовались как своего рода абстракция для EF. Я думаю, что такой подход убивает большинство преимуществ, увеличивающих скорость разработки, и приводит к нескольким вещам:
-
переназначение загрузки EF приводит к некоторому DTO, который убивает производительность (вызовите some select для получения данных таблицы - первый цикл, второй цикл - сопоставьте результаты с некоторым составным типом, сгенерированным ef, затем - отфильтруйте сопоставленные данные с помощью linq и, наконец, , сопоставьте его с некоторым DTO). Точное переназначение на DTO - убийца одного из самых больших преимуществ efs;
или 31
Speed of Development
Entity Framework Architecture
Entity Framework consists of the following three layers:
Data Providers
Data Provider layer is directly linked to the database. It is responsible to parse the query into a native SQL command expression in the database and then provide results back into domain objects of application.
You can insert a new user into data source by using an Entity Framework Code-First approach in the following example:
Entity Client
Entity Client is the core layer in Entity Framework, which connects the data source layer to the Object Service layer with the help of providers. It allows developers to write LINQ queries and read or write data without generating classes of conceptual schema.
Answers
As this is your first dive into working with a simple database application keep it simple by first not writing an application but instead learn either or way to interact with data via a console project e.g. do the CRUD operations, learn to do relationships etc. This is better than attempting to learn the database aspect coupled with the user interface and platforms. Consider the console project a throw-away project/ a do nothing project to learn with.
Make sure before even touching code to properly design your database based on what requirements you have to develop your app and to use for learning in the console project. Have a plan for populating data and scrubbing data after running unit test (unit test will dirty up data if you read/write to the database while another option is to use in memory unit test).
Personally I favor Entity Framework yet as Steve Falzon mentioned, it's all SQL at some level and that using a managed data provided may very well help to understand how things work while Entity Framework be it code first, model first or designer does not show everything like a managed data provider does (and I don't mean using TableAdapter or DataAdpater methods) using connection, command, data reader.
Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
Key Differences
Java Training (40 Courses, 29 Projects, 4 Quizzes) 40 Online Courses | 29 Hands-on Projects | 285+ Hours | Verifiable Certificate of Completion | Lifetime Access | 4 Quizzes with Solutions
4.8 (13,232 ratings)
When we go from the application layer to the database layer to find what is happening in an application this process of debugging is so embarrassing, whereas, the entity framework provides modeled relationships very clearly and their tiers are dependent, the storage model and the mapping can change without changing data classes, conceptual model or application code and data classes.
The maintainable code is the code that is easy to modify or extend we can also say that it is such type of code that is easy to understand and troubleshoot at anomalous conditions within the application we logged in even if they do not have errors.
Answered by:
4 ответа
Наконец: EF и LINQ дают много возможностей для поддержки ваших приложений позже.
В Entity Framework есть три разные модели: сначала модель, сначала база данных и сначала код, познакомьтесь с каждой из них.
-Точка об убийстве производительности, когда выполняется повторное сопоставление, потому что при первом запуске EF загружает метаданные в память, и это требует времени, поскольку он создает представление модели в памяти из файла edmx.
ORM позволяет разработчикам сосредоточиться на бизнес-логике приложения, что значительно сокращает объем кода.
Это устраняет необходимость в повторяющемся коде SQL и дает много преимуществ для скорости разработки.
Предотвращает написание SQL-запросов вручную; и многое другое ..
- В многоуровневом приложении это зависит от объема данных, которые ваше приложение обрабатывает и которыми управляет ваша база данных. Насколько мне известно, DTO не убивают производительность. Они представляют собой контейнер данных для перемещения данных между слоями и используются только для передачи данных и не содержат никакой бизнес-логики. В основном они используются в классах обслуживания. См. DTO.
- Один DBContext - всегда лучшая практика.
- Насколько мне известно, такой комбинации EF + SP (хранимая процедура) не существует. Если вы хотите использовать ORM, например EF, и SP одновременно, попробуйте микро-ORM, такие как Dapper, BLToolkit и т. Д. Он был создан для этой цели и чертовски быстрее EF. Вот хорошая статья о Dapper ORM.
Entity Framework в любом случае неэффективен, как в большинстве инструментов или наборов инструментов, предназначенных для достижения «более быстрых» результатов.
Доступ к базе данных следует рассматривать как отдельный уровень, использующий процедуры магазина в качестве интерфейса. Нет никаких причин для того, чтобы какое-либо приложение требовало более чем абсолютно необходимых операций CRUD. Меньше значит больше принципа. Хранимые процедуры легко писать, защищать, поддерживать и фактически являются самым быстрым способом. Легко написать инструменты для генерации желаемых кодов для POCO и DbContext с помощью хранимых процедур.
Хорошо спроектированное приложение должно иметь ограниченное количество строк подключения к базе данных, и ни одна из них не должна быть всемогущим Богом. Использование схемы для поддержки прав подключения.
Ленивая загрузка - это ложные утверждения, добавленные для решения проблемы, которая никогда не должна существовать, и возникшие в ORM и его функциях plug and play. Данные следует читать только при необходимости. Разработчики должны нести ответственность за реализацию этой логической базы в контексте приложения.
Если логика вашего приложения не может поддерживать состояния, никакие инструменты не помогут. Фактически, это только усугубит ситуацию, если будет скрывать настоящую проблему, пока не станет слишком поздно.
Сначала база данных - единственное решение для хорошо спроектированного приложения. Цивилизация давно осознала важность твердых акведуков и канализационных сетей. Код высокого уровня может и будет заменен в любое время, но данные останутся. Переписать все приложение - дело нескольких дней, если база данных хорошо спроектирована.
Приложения - это просто прославленный доступ к базе данных. По-прежнему верно в большинстве случаев.
Это мой вывод после многих лет отладки бизнес-приложений с помощью кодов, созданных множеством различных инструментов или наборов инструментов. Рекламируемые более быстрые результаты даже близко не покрывают количество времени / энергии, потраченного впустую на попытки навести порядок. Проблемы с производительностью редко, если не когда-либо, вызваны высоким спросом, а суммой всех «функций», добавленных с помощью непригодных для использования инструментов.
ADO. Net - это объектно-ориентированная среда, которая позволяет вам взаимодействовать с системой баз данных (SQL, Oracle и т. Д.). Entity framework - это методы управления данными в базах данных, например (сбор запросов (имя инертной таблицы, выберите * из вот так)). он используется с LINQ.
report this ad
report this ad
Overall – Final Thoughts
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 3 years ago .
How would you rate each of them in terms of:
- Performance
- Speed of development
- Neat, intuitive, maintainable code
- Flexibility
- Overall
I just want to check, that there isn't a great flaw in any of these technologies that would render my research time useless. E.g. performance is terrible, it's cool for simple apps but can only take you so far.
Update: Can you concentrate on EF VS L2S VS SPs rather than ORM VS SPs. I'm mainly interested by EF VS L2S. But am keen to have them compared against stored procs too since plain SQl is something I know a lot about.
@Sunil is correct, though not wordy enough. The issue is that everybody thinks their primary concern is app performance. When I talk about apps that require top performance, I think of hardcore C++ MMO's or high-volume customer-facing database transactions in the high millions. You really should focus on object-oriented principles like maintainability, readability, persistence ignorance and domain logic separation. Especially when performance increase is minor-at-best or non-existent in many cases.
This question is very useful to me. This is constructive question and may provide very useful information. Stackoverflow community should not consider this as not constructive +1 by me also.
What is Entity Framework?
You can make an application in an Entity Framework with minimal knowledge of database, because the framework is doing most of the operations and commands, and it is easy to implement CRUD operations in it. Therefore, it reduces development time and you can easily focus on the production instead of the databases.
Comparison Table
S.No | ADO.Net | EntityFframework |
1. | It provides a bridge between relational and non-relational systems. | Whereas, it is an object-relational mapping framework for ADO.Net which is an enhancement to ADO.Net. |
2. | It allows communicating between application and database. | Where it handles the database operations. |
3. | It uses the wrapper of entity framework so that by using it the development is faster, hence it gives the fast performance. | Whereas, this is not faster in performance. |
4. | It is directly connected to the database. | Whereas, the LINQ queries translate into SQL at first and then it processes the query. |
5. | It requires more time and more effort to build a complete structure of the data access layer. | Thus it requires less time and fewer efforts to handle the database operations. |
6. | It gives complete control to the data layer so that developers can create classes and methods. | Whereas it automatically creates the model and database, context classes. |
7. | In ADO.Net debugging is embarrassing as we go from the application layer to the database layer as it has maintainable code. | Whereas it provides a clear model relationship between entities and dependent tiers. |
8. | In ADO.Net, it performs bulk data SQL operations and reporting. | On the other hand, the entity framework performs the CRUD operations in a project. |
Conclusion
Never miss a post!
Sign up for our newsletter and get FREE Development Trends delivered directly to your inbox.
report this ad Categories
report this ad
Maintainable Code
Performance
Object Service
Object Service is the top layer in the Entity Framework architecture. It maintains the session between application and database. It performs CRUD operations with the help of queries. It represents the model entities of an application.
Flexibility
Recommended Articles
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
5 Answers 5
1) Performance
This is tricky to answer. For most single-entity operations (CRUD) you will find just about equivalent performance with all three technologies. You do have to know how EF and Linq to SQL work in order to use them to their fullest. For high-volume operations like polling queries, you may want to have EF/L2S "compile" your entity query such that the framework doesn't have to constantly regenerate the SQL, or you can run into scalability issues. (see edits)
For bulk updates where you're updating massive amounts of data, raw SQL or a stored procedure will always perform better than an ORM solution because you don't have to marshal the data over the wire to the ORM to perform updates.
2) Speed of Development
In most scenarios, EF will blow away naked SQL/stored procs when it comes to speed of development. The EF designer can update your model from your database as it changes (upon request), so you don't run into synchronization issues between your object code and your database code. The only time I would not consider using an ORM is when you're doing a reporting/dashboard type application where you aren't doing any updating, or when you're creating an application just to do raw data maintenance operations on a database.
3) Neat/Maintainable code
Hands down, EF beats SQL/sprocs. Because your relationships are modeled, joins in your code are relatively infrequent. The relationships of the entities are almost self-evident to the reader for most queries. Nothing is worse than having to go from tier to tier debugging or through multiple SQL/middle tier in order to understand what's actually happening to your data. EF brings your data model into your code in a very powerful way.
4) Flexibility
Stored procs and raw SQL are more "flexible". You can leverage sprocs and SQL to generate faster queries for the odd specific case, and you can leverage native DB functionality easier than you can with and ORM.
5) Overall
EDIT: EF 5 simplifies this part a bit with auto-compiled LINQ Queries, but for real high volume stuff, you'll definitely need to test and analyze what fits best for you in the real world.
Web development, programming languages, Software testing & others
Question
Please note that this is my first database application design,so i would like to give priority to learning relevant concepts over ease of use/development.
Please note that i plan to develop two separate applications (learning sake),
- one which logs to MYSQL server running locally
- another separate program that logs into an SQLITE database embedded within the application.
I would also like to run the programs cross platform(Windows and Ubuntu) using mono framework.
I am using Visual Studio Community edition on Windows 7.
Читайте также: