Posts Tagged ‘Entity Framework’

24
Jan

InfoQ interview with me

I was recently interviewed for InfoQ article – Q&A with Jiri Cincura of the Firebird Database Project. We touched Firebird, ADO.NET, O/RMs, Entity Framework etc. If you have any questions, feel free to ask.

15
Jan

Entity Framework 5.0!

Yesterday I wrote a post about a possible confusion that might be introduced with new version being version 5.0. Diego Vega wrote a follow up post describing the rationale behind it (and it was also noted in comments in previous post). Simply the team is now sticking to semantic versioning no matter what. Hope that will last a while. Let me recap.

The first version was, hey, version 1. The second version was version 4, because the numbering being unified with .NET Framework. Then there was a bunch of CTP, vNext, Preview, Alpha/Beta versions something being just update with version 4 core, something with new core. Hard to track what was what. Decision to use semantic versioning was made and the numbering was cleared a little, simply to 4.x and whatever version comes next. Still on track? Because of the semantic versioning rules, the next version is going to be 5. I thought the previous versioning decision would take precedence (though I think the .NET Framework version could be 5.0 as well) and it will be 4.5 as well.

I was wrong. The semantic versioning is now the way Entity Framework is going no matter what. Good. Hope the third version will be still using this scheme and will be version 6.

So. Next version is going to be version 5(.0.0) and will be delivered with .NET Framework 4.5.

13
Jan

Entity Framework 5.0???

There’s a follow up post.

I’m a little bit perplexed. Entity Framework 4.3 Beta 1 was just released. And there’s a sentence in the document that’s very interesting:

As soon as the next preview of the .NET Framework 4.5 is available we will be shipping EF 5.0 Beta 1, which will include all these new features.

Does it mean that the version that will ship with .NET Framework 4.5 (the next version in time of writing this post) is going to be 5.0? I still clearly recall the mess the second version with version number 4.0 created – a lot of people, on my trainings, talks, …, confused. What happened to clear versioning strategy?

I hope it’s just a small miss/typo and the version will be Entity Framework 4.5 and the following (additive) updates will be 4.5+n.

20
Dec

Mapping self references in Code First

From time to time I see people having problems to map self references in Code First in Entity Framework. It might be confusing what to do with HasMany/WithMany and HasOptional/WithOptional.

So let’s jump in. Define a pretty simple table:

create table SelfRefs (
  ID int primary key,
  FooBar varchar(20) not null,
  ID_Parent int
);

alter table SelfRefs add foreign key (ID_Parent) references SelfRefs(ID);

The corresponding class could be:

class SelfRef
{
	public int ID { get; set; }
	public string FooBar { get; set; }
	public SelfRef ParentItem { get; set; }
	public int? ParentItemID { get; set; }
	public ICollection<SelfRef> ChildItems { get; set; }
}

Now the mapping. The “trick” here is to realize, that we have not only child->parent association, but also parent->children. The other one is implied from the first one. Hence every child item has optional parent. If the child item has no parent, it is actually a 1st level child, aka child of (invisible) “root” (NULL parent). That also means you can map it from both directions and result will be the same. Here’s the example (it’s explicit a little more) with both mappings (you can use both declarations together without any problem):

class SelfRefConfiguration : EntityTypeConfiguration<SelfRef>
{
	public SelfRefConfiguration()
	{
		this.HasKey(x => x.ID);
		this.Property(x => x.ParentItemID).HasColumnName("ID_Parent");
		// starting from child with parent
		//this.HasOptional(x => x.ParentItem).WithMany(x => x.ChildItems).HasForeignKey(x => x.ParentItemID).WillCascadeOnDelete(false);
		// starting from parent with children
		this.HasMany(x => x.ChildItems).WithOptional(x => x.ParentItem).HasForeignKey(x => x.ParentItemID).WillCascadeOnDelete(false);

		this.Map(map =>
			{
				map.Properties(x => new { x.ID, x.FooBar, x.ParentItemID });
				map.ToTable("SelfRefs", "dbo");
			});
	}
}

Hope I made it a little bit more clear. If not, feel free to ask in comments.

19
Dec

ADO.NET provider for Firebird 2.7 released

I’m happy to bring you early Christmas gift packed as ADO.NET provider for Firebird version 2.7. This version brings important bug fixes (tracker.firebirdsql.org) and logging improvements.

This release wouldn’t be possible without support of people/companies using provider actively. Big thanks to them.

You can download it at www.firebirdsql.org or use NuGet package.

Enjoy!

11
Dec

Custom logic in every Entity Framework’s query

Few days ago there was a question on Twitter in #efhelp about adding custom logic to every query in Entity Framework. It’s pretty easy and you can do it absolutely transparently so nobody using your code needs to know.

First you need to focus you Entity Set (not Entity Type) in Model Browser window.

Here set the access modifier to i.e. private or (internal/protected) and rename it to something else, so it’ll not interfere with original name of property we’re going to create. I often use X prefix (especially for properties on entities).

Now it’s pretty easy to create some logic. Here I simply added filtering to always only fetch entities younger than 10 days from now.

partial class Model1Container
{
	public IQueryable<FooBarEntity> FooBarEntitySet
	{
		get
		{
			DateTime d = DateTime.UtcNow.AddDays(-10);
			return XFooBarEntitySet.Where(fb => fb.Created > d);
		}
	}
}

And that’s it. Not a difficult task. But also note that through Entity SQL (or i.e. reflection) somebody might be still able to access original entity set and get access to the data. So it’s not rock hard security solution.

21
Nov

Using database initializers with EDMX

Last week at my Entity Framework training I got a question whether you can use database initializer while still using EDMX file. The answer, as it turned out, isn’t that straightforward.

Directly you can’t. Because you need DbContext to create IDatabaseInitializer<T> (or to derive from default ones respectively). Even if you try to wrap ObjectContext into DbContext you’ll fail. The default objects are derived from EntityObjects and this is something that’s a showstopper for DbContext. So that’s a bad news.

On the other hand, there’s a good news, kind of. There’s a template (from Microsoft) to generate DbContext and classes from EDMX file.

With this template you will get all you need to start using database initializers. Only problem is, that you don’t have configurations generated from EDMX. But there’s also 3rd template, that can generate configurations (I haven’t tested it exhaustively).

Final answer? Yes you can, but it’s not smooth as it could be.

11
Nov

Improved #efhelp hashtag (cooperation with @EFHelp)

Few days ago we started using #efhelp hashtag for Entity Framework related questions. It’s starting well so far, but there was one small problem. Without a support from client application you can’t follow hashtag. That leaves you with the search “solution”.

To make it little bit more pleasant for people interested in #efhelp, I created a simple bot, that retweets everything with #efhelp under @EFHelp account. Hence now you can follow this account to be in picture. (Posting to that account does nothing and it’s not actively monitored.)

9
Nov

Entity Framework help on Twitter aka #efhelp

If you’re looking for a help related to Entity Framework and you’re on Twitter (mine is @cincura_net) you can try asking with hashtag #efhelp. Sure, no promises about getting reply, but this hashtag is monitored with a lot of skilled people. If it not fits into 140 characters, you might also find somebody willing to help you using different channel (i.e. email, on-site, …).

26
Aug

Stored procedures vs. indices and Entity Framework

Sometimes I came to discussion about Entity Framework not being able to use (map) particular stored procedure somebody wrote to do something very quickly and/or efficiently (kind of ;) ). You know, it’s boiling water for coffee, printing invoice and sending flowers to cafeteria girl down in a hall.

Not always this is a good optimization. Don’t get me wrong, I like stored procedures, if used properly. But sometimes the solution is easier. More and more are people forgetting about indices. Something databases are very good at using. And not only using, also maintaining and defining and so on. Proper index in heavily used query can make it order of magnitude faster. Especially for huge tables (when on proper fields).

The conclusion? Don’t immediately try to jump from sets and plain query definitions into imperative programming in stored procedures. Set operations are still very fast, database optimizers can do magic when it’s just query definition and indices are in place. And it’s way easier to live with index than to maintain stored procedure.

24
Aug

All and Any optimization in Entity Framework queries

When I’m teaching my Entity Framework trainings, I’m always begging to look, at least from time to time or when you see the query looks complex, to generated SQL statement. And if you have (near to) real data, also execution plan. Although Entity Framework helps you with standard data access layer, it’s not magic – the query translation is complex process and sometimes what you capture in LINQ query isn’t exactly how you’d express it in SQL. You simply have different concepts in LINQ vs. in SQL.

Last week I was writing some decision algorithms based on data and I was accessing it, of course, using Entity Framework. Because the conditions we’re complex I was writing these as it came from my head to my fingers. The day after I was writing similar condition, only one or two options negated and I wrote it differently. Basically I was swapping All and Any methods. These two are interchangeable, if you change conditions accordingly.

As an example let’s have and condition: “All apples are green.” aka “All(apple => apple.Color == Green)“. But you can also say “No (any) apple is non-green.” aka “!Any(apple => apple.Color != Green)“.

Now the magic comes to play. You might think, well, if it’s interchangeable, then it’s good, as Entity Framework can always utilize EXISTS predicate from SQL. For simple queries maybe. But if you think about various places where the condition can occur and how easy is to negate the condition you immediately have a lot of problems in front of you. Add to this database engine optimized, where it can or can’t use properly indices, reorder conditions to create smaller intermediate result sets etc. A lot of places where the machine needs to (try to) figure out what’s best way of getting your data for you.

Sadly there’s no rule of thumb, like always use Any. Only one good and 100% working advice is to always check the query and execution plan. But even with i.e. All the result could be absolutely fine.

12
Aug

SomeEntitySet.AddObject vs. AddToSomeEntitySet methods

Is it better to call ObjectContext.SomeEntitySet.AddObject() or ObjectContext.AddToSomeEntitySet()? Short answer is: It doesn’t matter.

Long answer. The AddToSomeEntitySet method calls base.AddObject("SomeEntitySet", someEntitySet);, you can see it from generated code. The other method calls base.Context.AddObject(this.FullyQualifiedEntitySetName, entity);. Hence it’s almost the same. Only difference is in FullyQualifiedEntitySetName property that is used. So it might be little bit slower, but I think it’s unmesurable difference. Also take into account other parts of your application, honestly, where you’re probably wasting more time. 8-)

What’s your preferred call?

10
Jul

Designer file in Entity Framework June 2011 CTP

There’s a lot of new stuff coming with the Entity Framework June 2011 CTP – enums and spatial types and … you can find it all around blogosphere. And for sure, I’ll cover my finding as I’ll dive into it. But there’s one, one could call it very minor, improvement, that was in, my opinion, pain in the ass.

Previously, the designer settings, like positions of lines for associations, sizes of entities and even zoom level were stored directly in EDMX file. Hence possibly creating changes in it even if you only read it. But the new CTP solves it. The designer’s content is now in a separate file. So if you’re about to commit to VCS you can much better see what was really changed – whether then model itself or only the designer (and you can ignore designer changes if you want).

Nice isn’t it? Pity that this “bug” made it to the first release. 8-)

3
Jun

ADO.NET provider for Firebird version 2.6.5 released

I’m proud to announce new version of ADO.NET provider for Firebird – 2.6.5. It’s half maintenance release, half new features.

You can find all bug fixes in tracker.

The new features include and improvements:
* Support for Trace API in Firebird 2.5.
* Improvements in SQL generation for Entity Framework.
* Support for commands logging .
* Slightly faster command execution of big queries.
* And a lot of small code improvement making it more stable…

You can download it at http://sourceforge.net/projects/firebird/files/firebird-net-provider/2.6.5/ or http://www.firebirdsql.org/en/net-provider/.

Hope you’ll enjoy the release.

18
May

Is Entity Framework Code First really third distinct option?

In a lot of articles the Entity Framework’s 4.1 Code First is described as third option to the already available so called Database First and Model First paths. But I’m not sure, it’s really a third distinct path. At least it’s not so clear.

Let’s describe what Database First means. You simply create a model by reverse engineering your current database. Then you can tweak the conceptual part and do the development. You’re not limited to work with generated classes, POCOs work too. Your model is described as XML file(s) (often in one file with EDMX extension).

The Model First goes the other way. You start with blank designer surface and at some time generate the SQL script to create database based on what’s on the surface. Of course you can use POCOs here as well. The model is stored in XML file, same as in Database First scenario.

But what the Code First does? Focusing only on important differences, it only allows you to save model as code (in any language being able to produce MSIL). Really. The only difference is the model representation, to be precise the mapping and kind of SSDL.

There’s no explicit conceptual part. You already have it. It is the objects you created – either generated or manually written both POCOs or derived from EntityObject class. The mapping and also the store model is described with your code. EntityTypeConfiguration, ComplexTypeConfiguration etc. classes directly or indirectly written. Also part of mapping could be inferred if you’re using conventions. And ultimately you can point this to an existing database or let the Entity Framework create it for you (or the SQL script). That’s when the database initializers (and providers) come to play.

Julia Lerman created a nice decision chart if you’re not sure what way to go. But in my eyes the only decision to make is whether you want to have everything in .NET code or in XML (and in fact, in runtime both approaches will create same in-memory representation).

Existing database & code ⇒ Code First
Existing database & XML ⇒ Database First
New database & code ⇒ Code First
New database & XML ⇒ Model First

See. So I think it’s more 2×2 options (and Code First being able to do two tasks) and we might call it: Code Database First, Code Model First, EDMX Database First and EDMX Model First or Database First with Code, Model First with Code, Database First with EDMX and Model First with EDMX. :)

6
May

Getting database script from DbContext (Code First)

I was speaking at Gopas Teched few days ago and there was a good question from audience about how to get the SQL script the DbContext is using to create database.

I never thought about it as I always create database in ER tool as it provides more features (like triggers, stored procedures etc.). But I remembered I implemented this method in .NET provider for Firebird. So it has to be somewhere.

The method is called CreateDatabaseScript and it’s on ObjectContext. So it was easy to expose it directly from DbContext, because it has ObjectContext under the hood (you can access it via IObjectContextAdapter).

public static string CreateDatabaseScript(this DbContext context)
{
	return ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript();
}

Hope the questioner will find this blog post.

22
Mar

Type mapper in Entity Framework 4.1

Even if you remove all conventions when using Code First you might get errors from Entity Framework about not being able to properly map some items. The reason is type mapper. In RC (and very probably in RTM as well) it’s not implemented as convention, hence always kicks in.

In this case the Ignore method comes into play. For instance I have in my code property:

public CultureInfo Locale
{
	get { ... }
	set { ... }
}

and I’m not mapping it at any place. But Entity Framework will still complain about pieces of CultureInfo not being properly mapped. But in EntityTypeConfiguration can make Entity Framework to ignore it. For example:

class FooBarConfiguration : EntityTypeConfiguration<FooBar>
{
	public FooBarConfiguration()
	{
		// ...
		this.Ignore(x => x.Locale);

		this.Map(...);
	}
}

At first I was confused, but after quick email exchange with EF team the “issue” was clear.

21
Mar

Removing all conventions in Entity Framework 4.1 Code First

Convention-over-configuration is great, at least for a quick start, in my opinion. But if you’re like me and you want everything under your control, you may want to remove all (at least those you can remove via code).

Because now there’s no list available (based on RC version, but very probably it’ll be same in RTM) as it was in i.e. CTP5 you need to kind of get all items implementing IConvention interface. And because I want my code work no matter what will be added or removed in next versions, I’m not going to hardcode these. Couple of lines with reflection and we’re done.

MethodInfo method;
method = typeof(ConventionsConfiguration).GetMethod("Remove");
foreach (var convention in Assembly.GetCallingAssembly()
	.GetTypes()
	.Where(t => t.Namespace == "System.Data.Entity.ModelConfiguration.Conventions" || t.Namespace == "System.Data.Entity.Infrastructure")
	.Where(t => t.GetInterface("IConvention", false) != null && !t.IsInterface && !t.IsAbstract))
{
	method.MakeGenericMethod(convention).Invoke(modelBuilder.Conventions, null);
}

I’m simply looking into System.Data.Entity.ModelConfiguration.Conventions namespace, where all the “I-do-the-mapping-for-you” conventions are and also System.Data.Entity.Infrastructure namespace, where the default database creation etc. stuff lives. The code is in overridden OnModelCreating method.

Now you can explore what one must do to create proper mapping by hand. :)

16
Mar

Entity Framework v4.1 Code First and Firebird

I do love Entity Framework. And you probably know it from the amount of weird ways to do some things published on this blog. And so I do love Code First. It’s like having all the power absolutely under control (or at least there’s a possibility to have it). And I also do love Firebird. It’s a great database engine. And I admit, it has strong as well weak points. But every engine does.

So there’s no wonder I’m using Entity Framework’s 4.1 (currently in CTP stage) Code First with Firebird. If you’re a bit lazy and you’re specifying only required minimum on information to run the mapping, you might quickly face one problem.

Long story. If you generated your model from database, the SSDL contained a lot of information about database structure. Especially lengths of (var)char fields. And these information were then used by provider for Firebird to create proper queries. But with Code First it’s bit boring to specify lengths for string fields moreover, when it works without it.

But the Firebird’s API has some limitations (especially around sizes of stuff) and by default (right now – CTP) the (var)char fields are 4000 characters long. The amount of (var)char parameters in code is limited (depends on few variables like charset, hence I’m not putting here exact number) and with UTF8 (multi-byte charset) it’s even more limited. And UTF8 is option #1 in .NET world.

All this together, couple of (var)char fields without length specified and you could start seeing Implementation limit exceeded and block size exceeds implementation restriction etc. The first place where you’ll see it is inserting, because there you have all the fields.

The solution is easy. Specify lengths explicitly and hope for the best. If the table is very wide (aka it doesn’t work), you could always split the table in more (yes, not great, but …).

16
Dec

EFv4 CTP5 some missing features (mapping)

Entity Framework v4 CTP5 added some new nice features since CTP4, for example the DbSet<T>.Local property I was blogging about or Validation. But, sadly, there’s something missing, mainly due to huge refactoring.

I hit the wall with one in particular. It’s entity splitting together with TPH inheritance. If you try to map it, you’ll get Entity splitting cannot be specified for type '<entity type>' since it is part of an inheritance hierarchy.. Bummer. So one of the projects I’m working on now, is stuck in CTP4. :)

On the other hand, the good news (from reliable source ;) ) is, that in RTM this will be working fine.

Next Page »