entity-framework-6 interview questions
Top entity-framework-6 frequently asked interview questions
I am trying to run my tests on TeamCity which is currently installed on my machine.
System.InvalidOperationException: System.InvalidOperationException
:
The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer
, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
for the 'System.Data.SqlClient
' ADO.NET provider could not be loaded.
Make sure the provider assembly is available to the running application.
See http://go.microsoft.com/fwlink/?LinkId=260882 for more information..
I have no reference to System.Data.Entity
in any of my projects as was suggested on codeplex for upgrading to EF6.
So, I am not sure why am I getting this exception.
I do not get any such exception when I run the tests from VS.
I did try to set CopyLocal to false then again to true.. but that does not seem to work either.
Update
My app.config has the following . Does this cause some behavior that I don't understand ?
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>
I get the following stacktrace in teamcity .
[MSTest] IntegrationTests.CrudTest+QuestionTest.Create
[03:59:11][IntegrationTests.CrudTest+QuestionTest.Create] Initialization method IntegrationTests.CrudTest+QuestionTest.Initialize threw exception. System.InvalidOperationException: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' for the 'System.Data.SqlClient' ADO.NET provider could not be loaded. Make sure the provider assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information..
[03:59:11]
[IntegrationTests.CrudTest+QuestionTest.Create] at System.Data.Entity.Config.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName)
at System.Data.Entity.Config.ProviderServicesFactory.GetInstanceByConvention(String providerInvariantName)
at System.Data.Entity.Config.DefaultProviderServicesResolver.GetService(Type type, Object key)
at System.Data.Entity.Config.CachingDependencyResolver.<>c__DisplayClass1.<GetService>b__0(Tuple`2 k)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at System.Data.Entity.Config.CachingDependencyResolver.GetService(Type type, Object key)
at System.Data.Entity.Config.ResolverChain.<>c__DisplayClass3.<GetService>b__0(IDbDependencyResolver r)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
at System.Data.Entity.Config.ResolverChain.GetService(Type type, Object key)
at System.Data.Entity.Config.RootDependencyResolver.GetService(Type type, Object key)
at System.Data.Entity.Config.ResolverChain.<>c__DisplayClass3.<GetService>b__0(IDbDependencyResolver r)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
at System.Data.Entity.Config.ResolverChain.GetService(Type type, Object key)
at System.Data.Entity.Config.CompositeResolver`2.GetService(Type type, Object key)
at System.Data.Entity.Config.IDbDependencyResolverExtensions.GetService[T](IDbDependencyResolver resolver, Object key)
at System.Data.Entity.Config.InternalConfiguration.GetService[TService](Object key)
at System.Data.Entity.Config.DbConfiguration.GetService[TService](Object key)
at System.Data.Entity.Utilities.DbProviderFactoryExtensions.GetProviderServices(DbProviderFactory factory)
at System.Data.Entity.Infrastructure.DefaultManifestTokenService.GetProviderManifestToken(DbConnection connection)
at System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
at System.Data.Entity.DbSet`1.Add(TEntity entity)
at EFRepository.Infrastructure.EFRepository`1.Add(T item) in c:\TeamCity\buildAgent\work\da2ea4e72c0e77f0\Repository\Infrastructure\EFRepository.cs:line 22
at IntegrationTests.CrudTest.Initialize() in c:\TeamCity\buildAgent\work\da2ea4e72c0e77f0\IntegrationTests\CrudTest.cs:line 34
Source: (StackOverflow)
I'm trying to build an EF Entity with Code First, and an EntityTypeConfiguration
using fluent API. creating primary keys is easy but not so with a Unique Constraint. I was seeing old posts that suggested executing native SQL commands for this, but that seem to defeat the purpose. is this possible with EF6?
Source: (StackOverflow)
Is there a way to find out whether there are unsaved changes in my entity context, in the Entity Framework?
Source: (StackOverflow)
What is the difference between System.Transactions.TransactionScope
and EF6's Database.BeginTransaction
?
Could someone give a small example or just explain which one to use when with a clear difference?
P.S: In my project, I'm using EF6. I've already read the documentation but it didn't help much. Also looked up the examples but they are rather using SqlConnection.BeginTransaction
and now MS has introduced this new Database.BeginTransaction
in EF6.
Source: (StackOverflow)
I can't believe I couldn't find a working solution to this after an hour of searching. I'm following this article on Entity Framework 6.0 which gives a simple walk-through on Code First. I created the project and installed the latest EF Nuget package for the project to compile. I also verified that I have Microsoft SQL Server 2012 Express LocalDB installed which came with Visual Studio 2013. I don't have any other instances of SQL installed on my local computer. The program runs and entries are added to the database and outputted in the console. But when the article says "check your localdb" it doesn't say how! I don't see any '.mdf' or '.ldf' files created under the project folder. I tried every way to connect Visual Studio's Server Explorer to LocalDB. The wizard cannot locate (localdb)
or cannot find any provider in Server Explorer to accept connection string like (localdb)\v11.0;Integrated Security=true;
I've seen this asked several places in StackOverflow but no answer works or marked as answer. Please help, this doesn't have to be this frustrating!
What are the steps to connect Visual Studio Server Explorer to LocalDB?
Source: (StackOverflow)
I am just starting out with Unit testings and TDD in general. I have dabbled before but now I am determined to add it to my workflow and write better software.
I asked a question yesterday that kind of included this, but it seems to be a question on its own. I have sat down to start implementing a service class that I will use to abstract away the business logic from the controllers and map to specific models and data interactions using EF6.
The issue is I have roadblocked myself already because I didn't want to abstract EF away in a repository (it will still be available outside the services for specific queries, etc) and would like to test my services (EF Context will be used).
Here I guess is the question, is there a point to doing this? If so, how are people doing it in the wild in light of the leaky abstractions caused by IQueryable and the many great posts by Ladislav Mrnka on the subject of unit testing not being straightforward because of the differences in Linq providers when working with an in memory implementation as apposed to a specific database.
The code I want to test seems pretty simple. (this is just dummy code to try and understand what i am doing, I want to drive the creation using TDD)
Context
public interface IContext
{
IDbSet<Product> Products { get; set; }
IDbSet<Category> Categories { get; set; }
int SaveChanges();
}
public class DataContext : DbContext, IContext
{
public IDbSet<Product> Products { get; set; }
public IDbSet<Category> Categories { get; set; }
public DataContext(string connectionString)
: base(connectionString)
{
}
}
Service
public class ProductService : IProductService
{
private IContext _context;
public ProductService(IContext dbContext)
{
_context = dbContext;
}
public IEnumerable<Product> GetAll()
{
var query = from p in _context.Products
select p;
return query;
}
}
Currently I am in the mindset of doing a few things:
- Mocking EF Context with something like this approach- Mocking EF When Unit Testing or directly using a mocking framework on the interface like moq - taking the pain that the unit tests may pass but not necessarily work end to end and back them up with Integration tests?
- Maybe using something like Effort to mock EF - I have never used it and not sure if anyone else is using it in the wild?
- Not bother testing anything that simply calls back to EF - so essentially service methods that call EF directly (getAll etc) are not unit tested but just integration tested?
Anyone out there actually doing this out there without a Repo and having success?
Source: (StackOverflow)
I've read through LOTS of posts on saving a detached entity in Entity Framework. All of them seem to apply to older versions of Entity Framework. They reference methods such as ApplyCurrentValues and ChangeObjectState which do not seem to exist. On a whim I decided to try a method I found through intellisense and I want to make sure this is the correct way to do this since I don't get to see what happening behind the scenes:
public void SaveOrder(Order order)
{
using (VirtualWebEntities db = new VirtualWebEntities())
{
db.Orders.Attach(order);
db.Entry(order).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
}
}
Is this the correct way to update an existing item that was changed?
Source: (StackOverflow)
I've got multiple classes (including TPT) in my project. Each POCO has a BaseClass
, which has a GUID
(called GlobalKey
) as primary key.
First I used DataAnnotations
to create correct foreign keys. But then I've got problems synchronizing the corresponding GUID with the object itself.
Now I want to have only one virtual navigation property so that the GUID field in the database is created by NamingConvention
. But the field name always adds an underscore followed by the word GlobalKey
(which is right). When I want to remove the underscore, I don't want to go thru all my POCOs in the fluent API to do this:
// Remove underscore from Navigation-Field
modelBuilder.Entity<Person>()
.HasOptional(x => x.Address)
.WithMany()
.Map(a => a.MapKey("AddressGlobalKey"));
Any ideas to do this for all POCOS by overwriting a convention?
Thanks in advance.
Andreas
Source: (StackOverflow)
I just downloaded entity framework 6 and created a brand new project to test it. We currently use EF 5.
After adding all my tables and stored procedures, I tried to build the project but I get errors:
Value of type 'System.Data.Objects.ObjectParameter' cannot be
converted to 'System.Data.Entity.Core.Objects.ObjectParameter'.
Value of type 'System.Data.Entity.Core.Objects.ObjectResult(Of
DataLibrary.MyStoredProc_Result)' cannot be converted to
'System.Data.Objects.ObjectResult(Of
DataLibrary.MyStoredProc_Result)'.
I cannot figure out why this will not work out-of-the-box
EF 5 had so such issues.
I am using VS 2012. .Net 4.5 Vb.net (also tried with a C# project... same issue)
Any ideas?
EDIT:
The answer was to install EF6 Tools for VS 2012. I did not know I had to do this since I thought that was installed when I added the Entity Framework package.
Source: (StackOverflow)
My application is using a database first EDMX in EF 4. I would like to upgrade everything to EF 6. After getting EF 6 with NuGet I had to make a lot of changes to my classes that are using my EF model, because namespaces have been changed in EF 6. Then I realized, that the code generated by my EDMX does also use the wrong namespaces etc. I'm not using a custom T4 so far.
How would I upgrade my existing EDMX to EF 6.
Thank you.
Source: (StackOverflow)
I have an entity with primary key "Id" which is Guid:
public class FileStore
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Path { get; set; }
}
And some configuration:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<FileStore>().Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
base.OnModelCreating(modelBuilder);
}
When I try to insert a record I get a following error:
Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated.
I don't want to generate Guid manually. I just want to insert a record and get Id
generated by SQL Server. If I set .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
, Id
column is not Identity column in SQL Server.
How can I configure Entity Framework to autogenerate Guid in SQL Server?
Source: (StackOverflow)
I installed EF 5.0 into the .DAL, now I want to install EF 5.0 into .BLL from Nuget
But the default online Nuget package always comes up with 6.0, which gives error when used together with the 5.0 EF I use in DAL.
Where can I install the 5.0 version of EntityFramework into my Nuget packages??
Source: (StackOverflow)
The first call to our API is always extremely slow. For example, below demonstrates the CPU usage and time it takes for the first call to complete:

The first call can take up to 30 seconds and eats almost 100% CPU. Call 2 and 3 take 200ms (as they should). After recycling the application pool, it will do the same thing with the first call.
I've read a bit about IIS "warm-up" and done the following, but nothing has changed:
IIS 8 Application Initialization is installed:

I have the following set in IIS:
- Set Start Mode to AlwaysRunning:

- Set the Recycling Timeout to 0:

- Set the Idle Time-out to 0:

- Set Preload Enabled to true on the site:

I am actually setting these in code in RoleEntryPoint.OnStart()
.
using (var serverManager = new ServerManager())
{
serverManager.ApplicationPoolDefaults.ProcessModel.IdleTimeout = TimeSpan.Zero;
foreach (var application in serverManager.Sites.SelectMany(x => x.Applications))
{
application["preloadEnabled"] = true;
}
foreach (var applicationPool in serverManager.ApplicationPools)
{
applicationPool.AutoStart = true;
applicationPool["startMode"] = "AlwaysRunning";
applicationPool.ProcessModel.IdleTimeout = TimeSpan.Zero;
applicationPool.Recycling.PeriodicRestart.Time = TimeSpan.Zero;
}
serverManager.CommitChanges();
}
I am almost certain that Entity Framework could be the culprit:
We are generating models from around 100 tables in a EDMX model "designer".
We are generating precompiled views generated by EF Power Tools.
The following initialization is running in Application_Start()
:
using (var context = new MyContext())
{
context.Database.Initialize(false);
}
I don't have these "initialization" problems when debugging.
The following tech is being used:
- .NET 4.5.1
- ASP.NET Web Api 2
- Entity Framework 6.1.1
- IIS 8 (Azure Web Role)
- Unity 3.5
Can anyone provide me with any other ideas or suggestions?
Source: (StackOverflow)
This is my code:
var banner = context.Banners.ToListAsync()
var newsGroup = context.NewsGroups.ToListAsync()
await Task.WhenAll(banner, newsGroup);
But when i called the function from controller. It showed error
A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.
Please help me solve this issue.
Source: (StackOverflow)
With EF6 you have a new transaction which can be used like:
using (var context = new PostEntityContainer())
{
using (var dbcxtransaction = context.Database.BeginTransaction())
{
try
{
PostInformation NewPost = new PostInformation()
{
PostId = 101,
Content = "This is my first Post related to Entity Model",
Title = "Transaction in EF 6 beta"
};
context.Post_Details.Add(NewPost);
context.SaveChanges();
PostAdditionalInformation PostInformation = new PostAdditionalInformation()
{
PostId = (101),
PostName = "Working With Transaction in Entity Model 6 Beta Version"
};
context.PostAddtional_Details.Add(PostInformation);
context.SaveChanges();
dbcxtransaction.Commit();
}
catch
{
dbcxtransaction.Rollback();
}
}
}
Is rollback actually needed when things go sideways? I'm curious because the Commit description says: "Commits the underlying store transaction."
Whereas the Rollback description says: "Rolls back the underlying store transaction."
This makes me curious, because it looks to me that if Commit isn't called, the previously executed commands will not be stored (which seems logical to me). But if that is the case, what would the reason be to call the Rollback function? In EF5 I used TransactionScope which didn't have a Rollback function (only a Complete) which seemed logical to me. Due to MS DTC reasons I cannot use the TransactionScope anymore, but I also cannot use a try catch like the example above (i.e., I only need the Commit).
Source: (StackOverflow)