background preloader

EF

Facebook Twitter

Расширения Entity Framework 6, о которых вы могли и не знать. Многие программисты делают записи, описывают трудности, красивые и не очень решения, с которыми приходится сталкиваться по долгу службы. Это может быть собственный технический блог, рабочая вики, или даже обычный блокнот — суть одна. Постепенно, из маленьких Evernote-заметок может вырасти целая статья на Хабр. Но время идет, перемена места работы сулит изменения в стеке разработки, да и технологии не стоят на месте (кстати, EF Core уже пару месяцев как в версии 1.1). С другой стороны, Entity Framework 6 был и остается "рабочей лошадкой" для доступа к данным в корпоративных приложениях на стеке .net, не в последнюю очередь благодаря своей стабильности, низкому порогу входа и широкой известности. Содержание: Database First без EDMXРабота с отсоединенными графамиМодификация SQL.

Database First без EDMX Не хотелось бы начинать очередной раунд спора "Code First vs. Решение кажется очевидным — необходимо отказаться от EDMX в пользу альтернативных средств генерации POCO и хранения метаданных. Entity Framework, Private Constructors and Private Setters. As I learn more and more from Domain Driven Design, my classes for DDD projects (those that are complex enough to need more than simple CRUD), are shifting from what are referred to as “anemic domain models” and more like “rich domain models”. The term “anemic domain model” (which I still have an aversion to…the term, that is) refers to a class that doesn’t really do much at all.

It has a bunch of properties and maybe some methods. To use them you instantiate or retrieve the object and then populate the properties at will. When working in DDD, the focus is on behaviors, not properties. So you would have methods to control what happens to your objects and in doing so, constrain the properties so that they are not exposed to be set or modified “willy nilly”. Here is an extremely simple pair of classes that are designed using some of the techniques I’m learning from DDD: I’m constraining the class so that anyone who instantiates it is required to pass in some values.

Entity Framework Performance and What You Can Do About It - Simple Talk. Compared to writing your own SQL to access data, you can become miraculously more productive by using Entity Framework (EF). Unfortunately, several traps that are easy to fall into have given it a reputation for performing poorly; but it doesn’t have to be this way! The performance of Entity Framework may once have been inherently poor but isn’t any more if you know where the landmines are.

In this article we’ll look at where these ‘traps’ are hiding, examining how they can be spotted and what you can do about them. We’ll use examples from a simplified school management system. There’s a database with two tables for Schools and their Pupils, and a WinForms app using an EF code-first model of this database to fetch data in a variety of inefficient ways. To play along at home, you can grab the code for most of these examples from – setup instructions are included in the readme. Database access Being too greedy with Rows … or even … A LINQ extension method to calculate a running total - blog.dee4star.com. The other day I needed to calculate a running balance based on a series of either debit or credit transactions. So each line item contains a balance column that is the carried forward balance plus the sum of debits and credits up until the current line item. After some playing around I came up with a simple LINQ expression to do the job. It is also a nice illustration of how LINQ expression trees enable you to create more elegant solutions.

Lets start by create a simple object: public class LineItem{ public decimal Debit { get; set; } public decimal Credit { get; set; } public decimal Balance { get; set; }} Now lets create some sample data: List<LineItem> items = new List<LineItem> { new LineItem { Debit = 100, Credit = 0 }, new LineItem { Debit = 0, Credit = 1000 }, new LineItem { Debit = 0, Credit = 200 }, new LineItem { Debit = 50, Credit = 0 }, new LineItem { Debit = 300, Credit = 0 }}; Notice I haven't set the Balance (I am just letting it default to zero). Return list; }} return list;} Rollup Extension Method: Create Running Totals using LINQ to Objects - Eric White's Blog. Recently, I had need for a new extension method for IEnumerable<T>, which I call "Rollup". This extension method is sort of a cross between the Select and Aggregate extension methods.

Like Select, when using this extension method you write a lambda expression to project the new value in a new collection. Unlike Select, in the projection lambda expression, you are passed the projected value for the immediately preceding element. The previous value for the first element in the projected collection is a seed value that you pass to the Rollup extension method. This blog is inactive.New blog: EricWhite.com/blogBlog TOCThis extension method has use in two situations. Int[] a = new [] { 3, 1, 4, 1, 5, 9 };var runningTotal = a.Rollup(0, (s, x) => s + x);foreach (var i in runningTotal) Console.WriteLine(i); This outputs: The first argument to Rollup is the seed (0, in this case).

Here is the implementation of the Rollup extension method. And as you might expect, this produces: DATE \@ "dd, MM" \h. SQL Joins with C# LINQ. Posted By : Shailendra Chauhan, 18 Oct 2012 Updated On : 25 Nov 2013 Keywords : linq join on multiple conditions,c# join example, linq inner join with multiple conditions, linq left outer join, linq left join, linq cross join, linq right join, linq group join There are Different Types of SQL Joins which are used to query data from more than one tables. In this article, I would like to share how joins work in LINQ. The JOIN query operator compares the specified properties/keys of two collections for equality by using the EQUALS keyword. LINQ PAD for running and debugging LINQ Query I am a big fan of LINQ Pad since it allow us to run LINQ to SQL and LINQ to Entity Framework query and gives the query output.

In this article, I am using LINQ PAD for query data from database. Inner join returns only those records or rows that match or exists in both the tables. C# Code LINQ Pad Query INNER JOIN among more than two tables INNER JOIN On Multiple Conditions LEFT JOIN or LEFT OUTER JOIN C# Code. SQL Joins with C# LINQ. Entity framework | RiggsHill Software. There are two flavors of serialization you can use on Framework entities: good ol' XML serialization and the DataContract serialization. XML serialization is pretty straightforward - it serializes the object it's given. But it does not walk references (I'm talking foreign keys here) or collections. whereas the DataContract serializer does handle the references and keeps track of what objects have been serialized and what hasn't.

If you're going to use XSLT on the serialization, I'm not sure at this point which one is better - they're probably equal but time will tell. Unfortunately you can't directly serialize the entire ObjectContext, only collections or individual objects can be serialized. But this isn't as bad as it sounds as usually you'll want to start at some 'master object' in a collection and serialize it and all it references, so the inability to directly serialize the Context is not a big loss. So how do you do it? First find the Recipe: Then setup the serializer: That's it. MainModule.vb. Managing BLOBs using SQL Server FileStream via EF and WCF streaming | Peter Meinl: Software Development Tips.

Public Interface IDocumentService <OperationContract()> Sub SaveDocument(documentInfo As DocumentInfo) <OperationContract()> Function GetDocumentKeysByFullText(searchCondition As String) As List(Of DocumentKeys) <OperationContract()> Function GetDocument(ID As Guid) As System.IO.Stream End Interface Public Class DocumentInfo <MessageBodyMember()> Public DocumentStream As IO.Stream <MessageHeader()> Public FileName As String <MessageHeader()> Public DocumentStreamLength As Long End Class Public Class DocumentKeys <DataMember()> Public ID As Guid <DataMember()> Public Name As String Public Class DocumentService Implements IDocumentService, IDisposable Private Shared _readCommittedTransactionOptions As New TransactionOptions With {.IsolationLevel = Transactions.IsolationLevel.ReadCommitted, .Timeout = TransactionManager.DefaultTimeout} Class FileStreamContext Public Property InternalPath As String Public Property TransactionContext As Byte() _trace.Debug("") Dim stw = Stopwatch.StartNew Dim ID = Guid.NewGuid.

EF Code First Extras. Tracing and Caching for Entity Framework available on MSDN Code Gallery - Jaroslaw Kowalski. We have just released a sample that shows how to extend Entity Framework in interesting ways by plugging into ADO.NET provider interface. The sample provides two extensions: EFTracingProvider – which adds the ability to log all SQL commands that are executed (similar to LINQ to SQL’s DataContext.LogEFCachingProvider – which adds transparent query results cache to EF The sample comes with implementation of distributed cache which uses Velocity CTP 3 as well as an adapter for ASP.NET and simple in-memory cache implementation. Because the sample is quite large and uses many advanced techniques, it’s impossible to fully explain it all in one blog post. In this first post I’ll briefly explain the idea of wrapper providers and describe the new the APIs exposed by EFTracingProvider and EFCachingProvider.

In future posts I’ll try to explain more technical detail details and provide advanced logging/caching tips. Provider Wrapers The wrapper provider gets a chance do interesting things, such as: Tip 14 - How to cache Entity Framework Reference Data - Meta-Me. Scenario: In order to make applications perform it makes a lot of sense to cache commonly used reference data. Good examples of reference data include things like States, Countries, Departments etc.

Generally you want to have this data readily at hand, so you can populate dropdown boxes etc. A good example where caching reference data might be handy is a web page for signing up new customers, part of the form collects the customers address, including their State. To build the State drop down for the form. So how do you support this sort of scenario using the Entity Framework? Solution: When designing the solution we need to remember 2 key points. An Entity, at least in .NET 3.5 SP1, can only be attached to one ObjectContext at a time. Essentially these two points are at odds with one another. The solution is to clone Entities whenever we read from the Cache, this way attaching clones won't affect any other threads. But this has one big problem. Why? Or as a lambda something like this: Exposing the ORM Cache. Related Content Browse this Topic: Queue on Reddit Exposing the ORM Cache Familiarity with ORM caching issues can help prevent performance problems and bugs.

In the early 1990s, when object-oriented languages emerged into the mainstream of software development, a noticeable surge in productivity occurred as developers saw new and better ways to create software programs. Although the new and efficient object programming paradigm was hailed and accepted by a growing number of organizations, relational database management systems remained the preferred technology for managing enterprise data. Thus was born ORM (object-relational mapping), out of necessity, and the complex challenge of saving the persistent state of an object environment in a relational database subsequently became known as the object-relational impedance mismatch. Complex problems sometimes demand complex solutions, and ORM software is no exception. Caching is generally recognized as being vital to performance optimization. Доступ к данным - Second-Level Caching in the Entity Framework and AppFabric.

ObjectContext и DbContext в Entity Framework (EF) поддерживают информацию о состоянии сущностей, которыми они управляют. Но, как только контекст выходит из области видимости, данная информация перестает быть доступной. Это называют кешированием первого уровня, и оно действует лишь в течение жизненного цикла транзакции. Если вы пишете распределенные приложения с применением EF, где контекст часто меняется (а значит, ваша информация о состоянии доступна не всегда), кеширование первого уровня вряд ли обеспечит ваши потребности.

Такая ситуация типична для веб-приложений и сервисов — или даже когда вы используете какой-то тип реализации шаблона хранилища, где длительно выполняемый контекст недоступен. Почему EF может выиграть от кеширования второго уровня Для чего нужен доступ к представлению исходного состояния между процессами? Кеши второго уровня играют важную роль в решении проблем такого рода. Рис. 1. Использование провайдера кеширования EF для добавления кеша второго уровня Рис. 2. Tracing and Caching Provider Wrappers for Entity Framework in C# for Visual Studio 2010. Repository, Specification, Unit of Work, Persistence Ignorance POCO with Microsoft ADO.NET Entity Framework 4.0 Beta 2 « KITCHAIYONG.NET.

Preface As of preparing this writing and the source codes, I was using the .NET Framework 4.0 Beta 1, Visual Studio 2010 Beta 1 and ADO.NET Entity Framework Feature CTP 1. However, the .NET Framework 4.0 Beta 2 and Visual Studio 2010 Beta 2 made their debut on 21 October 2009. I decided to upgrade the projects to this latest beta 2 version. So, the requirements to run the sample projects that come with this post has changed to .NET Framework 4.0 Beta 2 and Visual Studio 2010 Beta 2 which you can download them at this address, I am using the Visual Studio 2010 Ultimate Beta 2 which is downloadable as ISO file at So you can run the sample projects without the EF CTP Preview 2. For my onward posts on Microsoft technologies, my work will base on the same sample projects for this post which you can download at end of this post.

Happy reading. Okay. Figure 1.0 General Repository Diagram. .NET Junkie - Faking your LINQ provider part 1. Friday, someone at Stackoverflow asked how to hide LINQ enabled persistence frameworks behind an abstraction (the repository pattern). I pointed him to a question on Stackoverflow that I answered a few days earlier in what I explained how to allow your LINQ to SQL project to be unit testable.

Friday’s question however, was about being able to easily change the O/RM later on, and specifically with multiple data stores / databases involved. Let me start by saying that due to the current difference in behavior and quality between both open source and commercial LINQ provider implementations, it is hard to completely abstract away such implementation, while still allowing to use LINQ to Expression queries that are effectively translated to database queries.

For the project I'm currently working on, I use LINQ to SQL as O/RM tool and I was faced with the problem of unit testing. I wrote this answer on Stackoverflow with the experience gained on this project. Unit of Work return entity; }} Asp.net mvc 3 - MVC, EF - DataContext singleton instance Per-Web-Request in Unity. Generic Repository Pattern - Entity Framework, ASP.NET MVC and Unit Testing Triangle. IMPORTANT NOTE: I have a new blog post about Generic Repository implementation for Entity Framework. Please check it out instead of this one: Clean, Better, and Sexier Generic Repository Implementation for Entity Framework NOTE:Entity Framework DbContext Generic Repository Implementation Is Now On Nuget and GitHub: DRY: Don’t repeat yourself which is a principle of software development aimed at reducing repetition of information of all kinds, especially useful in multi-tier architectures. That’s what Wikipedia says. In my words, if you are writing the same code twice, follow these steps: Step back.

That’s what I have done for repository classes on my DAL projects. First approach (worst approach) At first, long time ago, I have been creating all the single methods for each interface. This repo is for Foo class I have (imaginary). A better approach but still sucks. О разработке ПО и эффективности: Code First Migrations + Entity Framework 4.3 Beta 1. Mapping private/protected/… properties in Entity Framework 4.x Code First | Jiří {x2} Činčura.

Advanced Data - Programming ASP.NET MVC 4 Web Applications. Testability and Entity Framework 4.0. Mvc & jQuery CMS - The Repository Pattern with EF code first & Dependeny Injection in ASP.NET MVC3. Entity Framework POCO (EF4): Generic Repository and Unit of Work Prototype. POCO in the Entity Framework : Part 3 – Change Tracking with POCO - ADO.NET team blog. Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application (9 of 10) ObjectContext Undo, Cancel? Developing web apps using ASP.NET MVC 3, Razor and EF Code First - Part 1 - Shiju Varghese's Blog. EF Feature CTP5: Pluggable Conventions - ADO.NET team blog.