How to know project is code-first or database-first? - c#

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.

Related

cannot perform override in class inheritance in ADO .NET Entity Model edmx

I have to build a .net web application accessing tables of an existing db.
The db uses different tables for different companies: customers in company "ACorp" are stored in table "ACorpCustomers", those in company "B" are stored in table "BCorpCustomers".
Using ADO .NET Entity Model, I created a different Db Context for each Company:
public partial class ACorpContext : DbContext
{
public ACorpContext()
: base("name=ACorpContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<ACorpCustomer> ACorpCustomers { get; set; }
}
}
The edmx generates also the class
public partial class ACorpCustomer
{
public string Name { get; set; }
public string Phone { get; set; }
}
I created a parent class Customer to be used in the application, with the same properties:
public class ACorpCustomer
{
public virtual string Name { get; set; }
public virtual string Phone { get; set; }
}
I havent't found a way to let the specific entity ACorpCustomers inherit from the parent Customer; the edmx returns the inheritance error, but there is no way to override the properties.
Update
In order to avoid edmx file usage, this is what I finally tried out:
I disabled the __MigrationHistory sql table creation using the AutomaticMigrationsEnabled parameter:
internal sealed class Configuration : DbMigrationsConfiguration<MyDomain.Models.ACorpContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
}
I disabled the db initialization in the App.config file setting
disableDatabaseInitialization="true"
Then I added a an ADO .NET Entity Model but chose the "code first from database".
In order to be sure not to change the db from the model, I disabled the DB Initializer:
public ACorpContext()
: base("name=ACorpContext")
{
Database.SetInitializer<ACorpContext>(null);
}
Now I expect to be my responsability to be keep in sync the domain model with the db.
Anyway, I feel sure that in case of misalignment no attempt will be done to modify the db.
Without the edmx, I have no more limitations defining inheritance from an abstract class Customer.
I cannot understand why Visual Studio considers this as "Code First" approach, anyway.
Your definition
public partial class ACorpCustomer
has nothing to do with inheritance. partial is a .NET moderator that signifies that your class definition is a part of the bigger definition. For example if you have your class split between 2 code files. .Net "puts" them together and you endup with one type
Here what you seem need to do is
public abstract class Customer
{
public string Name { get; set; }
public string Phone { get; set; }
}
public class ACorpCustomer : Customer
{
// may be, some unique properties here
}
public class BCorpCustomer : Customer
{
// may be, some unique properties here
}
The properties Name and Phone don't even need to be virtual. Looking back into your title, there is nothing that you need to override. Nothing that I see..
This is trivial in Code-First, which you can (and should) use with an existing database. Just map the single Customer entity to the correct table for each DbContext:
public partial class ACorpContext : MyBaseDbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().ToTable("ACorpContext");
}
public virtual DbSet<Customer> Customers{ get; set; }
}

Consuming View in EF Code First conflicts with migration

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.

Entity Framework entity can't be found in dbcontext auto-generated code

I use entity framework 6.1.3 model first approach.
I needed to design a simple model as following.
Then i generated sql to create the database but i found that my entities sets were not defined in my DbContext. I tried to add them manually but Entity Framework keeps regenerating the following code.
It only generates the abstract entity which is exactly the opposite of what it is designed for.
public partial class UploadsDataModelContainer : DbContext
{
public UploadsDataModelContainer()
: base("name=UploadsDataModelContainer")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<AzureBlobs> AzureBlobs { get; set; }
}
Is this a bug in EF code generator or am i missing a step in model creation ?
Thanks to RicardoPeres i added a class file with the following content and it resolved my problem by avoiding the automatic updates of the DbContext.cs file :
public partial class UploadsDataModelContainer : DbContext
{
public virtual DbSet<Chunk> CHunks { get; set; }
public virtual DbSet<Upload> Uploads { get; set; }
}

Code-first: Mapping entities to existing database tables

I am using Entity Framework 6 code-first with an existing database, but having problems mapping my entities to the database tables.
Normally, I would use database-first approach and have my entity and context code generated, but using the designer has become a huge pain.
I have set Database.SetInitializer(null) as I do not want EF to change my schema.
Database schema:
Code-first:
public class Project
{
public int ProjectId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class ReleaseControlContext : DbContext
{
public ReleaseControlContext()
: base(ConfigurationManager.ConnectionStrings["ReleaseControl"].ConnectionString)
{
Database.SetInitializer<ReleaseControlContext>(null);
}
public DbSet<Project> Projects { get; set; }
}
Calling code:
using(var context = new ReleaseControlContext())
{
var projects = context.Projects.ToList();
}
The following exception is thrown:
SqlException: Invalid object name 'dbo.Projects'.
This is because my database table is Project and not Projects. I don't want to rename my context's DbSet<Project> to "Project" because that would be semantically incorrect.
Question:
Do I have to use the fluent API/data annotations to map between the Project database table and the DbSet<Project> Projects collection?
You can use the
[Table("Project")]
public class Project {
....
}
annotation against the Project entity, or in the OnModelCreating(DbModelBuilder modelBuilder) you can call modelBuilder.Entity<Project>().ToTable("Project");.
Both would do the same thing.
You should define a class (ie:ProjectMap) that inherits from the generic class EntityTypeConfiguration(T) where T is here your Project class.
In this ProjectMap class, you can define explicitly a table mapping :
this.ToTable("Project", "dbo");
The class ProjectMap should be called in the following method of your DbContext class
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ProjectMap());
}

Infrastucture does not exist in System.Data.Entity

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 ...)

Categories