There seems to be something strange happening with regards to adding an entity set to an existing project vs having an entity set in its own project for re-usability.
Scenario One
Project A is a class library and has an EF set added to it and connected to a database.
Within the default class in the class library project, this code is written and compiles fine.
public void test()
{
using (var context = new Accu_CRM_dbEntities())
{
var test = context.BillableParts.First(P => P.Id == "test");
}
}
Scenario Two
Project B is another project added to the same solution. A reference is made to project A so as to use the identities in project B. A using statement is placed in the code file that is going to be making dB calls with the EF set. The same code is written into project B; however, the compiler complains that 'DAL.Accu_CRM_dbEntities': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Aside from this, all intellisense support is lost when dealing with the context.
If I type context.BillableParts. intellisense support ceases after the entity name. What exactly is the reason that project B cannot see that Accu_CM_dbEntities should be disposable the way it is in project A?
namespace DAL
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class Accu_CRM_dbEntities : DbContext
{
public Accu_CRM_dbEntities()
: base("name=Accu_CRM_dbEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<BillablePart> BillableParts { get; set; }
public virtual DbSet<BillableService> BillableServices { get; set; }
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<Part> Parts { get; set; }
public virtual DbSet<PartsManufacturer> PartsManufacturers { get; set; }
public virtual DbSet<WorkOrder> WorkOrders { get; set; }
}
}
Perhaps some more information on the database would have been a bit more useful. I am using SQL server compact. I used nuget and installed EF for sql compact within my consuming project (consumer of EF project) and everything was fixed. I am not 100% sure what was the issue exactly but obviously I did not have the correct libraries referenced. I'll leave this up here for anyone else that might be getting this error
Related
I have a Table "IncomingChecks" in my database. I've created it using EF Code first. Now, I've added a view to my database based on this table named "ViewIncomingChecks" using Sql Server Management Studio and I want to use its data in my app using Entity Framework.
I copied the model class and changed its name and added it to the context:
public class ViewIncomingCheck
{
[Key]
public int Id { get; set; }
//...
}
public class CheckDataContext : DbContext
{
public virtual DbSet<ViewIncomingCheck> ViewIncomingChecks { get; set; }
//...
}
now when I run the app, it throws an exception saying the DB Context has been changed and needs a migration. I even tried to add a migration (which seems to be the wrong option) and when I add the migration, it says that the object ViewIncomingChecks is already in the database.
How can I use this view in my code?
Edit
My current solution is to have another context just for the views. This way it doesn't conflict with the EF Migrations. Is this the best option or is there a better way to deal with it.
According to what I have done in my project:
First add public virtual DbSet<ViewIncomingCheck> ViewIncomingChecks
{ get; set; } to your DbConext
Now create a migration something called ViewDbSetAdded
Remove all the code from the both Up and Down method and it will look like as follows:
Migration Code:
public partial class ViewDbSetAdded : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
Now run update-database command and it will run an empty migration.
In an existing project, how do I know if it's code-first or database-first?
Project has this lines of code:
public class TestDBContext : DbContext
{
public DbSet<Player> Players { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
And project has no .edmx file. If any other details need I will share.
EDIT:
Player.cs class
public class Player
{
public int PlayerID { get; set; }
public string PlayerName { get; set; }
}
EDIT 12.05.2017
IF I change database name from connection string and run project, it creates database with the new name with all tables. May be this will be hit for the answer.
If this is a project is Database-first, there is :
[name].edmx diagram file and with it, [name].Context.tt & .cs
every tables that are translated into class are hidden in tree like .edmx > .tt
in OnModelCreating, there is a throw new UnintentionalCodeFirstException()
If not, all the class issue from the tables are in the project (no tree).
Here I am sharing my observation.
Mainly there are two approaches to implement Entity Framework.
1. Code-first
If chosen, it will create simple .cs file(s) which developers later modifies as per their requirement.
Data-first
If chosen, it will create a [name].edmx file along with hierarchy of different files. It contains .Context.tt and underneath .Context.cs file.
The .Context.cs file will have below snippet which indicates whether induced entity model was empty when created or it was with any database object.
namespace Search
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class XYZ_MSCRMEntities : DbContext
{
public XYZ_MSCRMEntities()
: base("name=xyz_MSCRMEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<AnyDatabaseTableOrView> TableOrViewPluralized { get; set; }
}}
In above snippet, very last line (DbSet property) shows that it has imported database object and that is how it is "Data-first"
If there is no .edmx file, the project is code-first.
These are my models:
public class Application
{
public Guid ID { get; set; }
public virtual Project MainProject { get; set; }
public virtual ICollection<Solution> Solutions { get; set; }
}
public class Solution
{
public Guid Id { get; set; }
public virtual Application Application { get; set; }
public virtual ICollection<Project> Projects { get; set; }
}
public class Project
{
public Guid Id { get; set; }
public virtual ICollection<Solution> Solutions { get; set; }
}
So basically, an Application has a list of Solutions, and a Solution has a list of Projects. An Application also has a Main Project (which will be somewhere in the group of Projects that is accessible through the Application's Solutions, but that's not forced by the DB).
I've got an issue when I try to add a new Application that has the MainProject property set.
Unable to determine a valid ordering for dependent operations.
Dependencies may exist due to foreign key constraints, model
requirements, or store-generated values.
I don't understand what the problem is. MainProject is not mandatory, in fact the insert works if I don't set that property. There is a circular dependency, but there is a clear order that works
Insert application with no main project
Insert solutions
Insert projects
Update application to set relevant project as main project.
Is there any way to tell Entity Framework to do this?
edit:
Here are the configurations:
public ApplicationConfiguration()
: base()
{
HasKey(a => a.ID);
ToTable("Applications");
HasOptional(a => a.MainProject);
}
public SolutionConfiguration()
: base()
{
ToTable("Solutions");
}
public ProjectConfiguration()
: base()
{
ToTable("Projects");
}
You can configure this in the DbModelBuilder using the fluent api or in the Entity Models using data annotations. Basically, you have to tell EF which Entity is the principal end and which is the dependent (think cascade delete...).
For example, if Application is the principal and there can be 0 or 1 MainProject, and MainProject shall not exist without Application, and MainProject shall be deleted when Application gets deleted:
ModelBuilder.Entity<Application>().HasOptional(a => a.MainProject).WithRequired().WillCascadeOnDelete(true);
Application has many Solutions, and Application is required for a valid Solution, with backlink:
ModelBuilder.Entity<Application>().HasMany(a => a.Solutions).WithRequired(s => s.Application);
Solution has many Projects, with backlink:
ModelBuilder.Entity<Solution>().HasMany(s => s.Projects).WithMany(p => p.Solutions);
See Configuring Relationships with the Fluent API
I have a simple Entity Framework Code First context for persisting events as they arrive from the bus. The context is :
public class MyContext : DbContext
{
public MyContext (DbConnection connection)
: base(connection, false)
{
Database.SetInitializer<MyContext>(null);
Configuration.AutoDetectChangesEnabled = true;
}
public DbSet<MyEvent> MyEvents { get; set; }
}
where MyEvent is
public class MyEvent
{
public int Id { get; set; }
public string Source { get; set; }
public string MessageId { get; set; }
public DateTime EventDate { get; set; }
}
Now, when I try to access the context.MyEvents collection I get a ReflectionTypeLoadException
Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
with LoaderException
"Method 'ToCombinedRows' in type 'XXXX' from assembly 'YYYY' does not have an implementation."
Now this is really strange as the type XXXX is completely unrelated to the object being persisted and has no reason to have a method of this name.
All the objects are defined in the same assembly, and I am running from an integration test project, with references CopyLocal set to true. Does anyone know how to get my context to talk to the database?
Ok, found the problem.
I was running the integration tests using ReSharper, which loads the assembly into a temporary location, and Entity Framework could not work out the types in that location (it was fine when I ran from a Console app). For reasons that I do not know, when I split the context objects into their own assemblies, Entity Framework ran fine. So, not a problem with the references in the project, just a problem loading these references into the test harness.
I am trying to create MVC project with Entity Framework.
I have 3 Projects in Solution
SerialTracker.Common
SerialTracker.Model
SerialTracker.Web
Common and Model are compiled like library, so Web is using them.
Model is also using Common.
My probelm is here:
Model generate from *.edmx ==> *.Context.tt ==> whitch auto generates *.Context.cs:
namespace SerialTracker.Model
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class SerialTrackerEntities : DbContext
{
public SerialTrackerEntities()
: base("name=SerialTrackerEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Role> Role { get; set; }
public DbSet<User> User { get; set; }
}
}
I have error, that Infrastucture does not exist in System.Data.Entity. I tried adding some References, but i think the problem is in another place.
//EDIT:
I reinstaled NuGet package for this project, but now i have error and doesn't exist
Sorry for my poor English.
S̶o̶ ̶I̶ ̶m̶a̶n̶u̶a̶l̶y̶ ̶a̶d̶d̶e̶d̶ ̶f̶i̶l̶e̶ ̶S̶e̶r̶i̶a̶l̶T̶r̶a̶c̶k̶e̶r̶.̶t̶t̶ ̶t̶o̶ ̶S̶e̶r̶i̶a̶l̶T̶r̶a̶c̶k̶e̶r̶.̶e̶d̶m̶x̶.̶
T̶h̶i̶s̶ ̶f̶i̶l̶e̶ ̶I̶ ̶c̶o̶p̶i̶e̶d̶ ̶f̶r̶o̶m̶ ̶a̶n̶o̶t̶h̶e̶r̶ ̶p̶r̶o̶j̶e̶c̶t̶.̶
N̶o̶w̶ ̶i̶s̶ ̶p̶r̶o̶j̶e̶c̶t̶ ̶g̶e̶n̶e̶r̶a̶t̶e̶ ̶e̶n̶t̶i̶t̶i̶e̶s̶ ̶R̶i̶g̶h̶t̶.̶
EDIT (04-29-2014):
Renewed answer:
You can delete file *.tt and recreate it with
Add -> New Item -> EF 5.x DbContextGenerator (or EF 6.x ...)