I have an EF6 Database-First application that adds to a table. The Model appears to have generated perfectly (T4) and intellisense shows exactly what I'd expect at design-time.
However, at runtime, the exception:
The entity type UsedLoanNumbers is not part of the model for the current context."
occurs on the line that first references the UsedLoanNumbers entity:
using (var context = new NLNEntities())
{
UsedLoanNumbers uln = context.UsedLoanNumbers.Last();
uln.UserID = userID;
uln.AssignedDateTime = DateTime.Now;
uln = context.UsedLoanNumbers.Add(uln);
this.LoanNumber = uln.LoanNumber.ToString();
context.SaveChanges();
}
I do have a second EF context in a separate DLL that does logging... They are named completely different, but are both modifying data in the same database:
What am I doing wrong?
Here's the context code:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace NewLoanNumber
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class NLNEntities : DbContext
{
public NLNEntities() : base("name=NLNEntities") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<ErrorLogging> ErrorLoggings { get; set; }
public virtual DbSet<LogEntryPriority> LogEntryPriorities { get; set; }
public virtual DbSet<LogEntryType> LogEntryTypes { get; set; }
public virtual DbSet<ProcessLog> ProcessLogs { get; set; }
public virtual DbSet<UsedLoanNumbers> UsedLoanNumbers { get; set; }
}
}
Connection strings:
name="NLNEntities" connectionString="metadata=res://*/LoggingModel.csdl|res://*/LoggingModel.ssdl|res://*/LoggingModel.msl;provider=System.Data.SqlClient;provider connection string="data source=CSTestLSDW;initial catalog=LoanServicingDW;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
name="LoggingEntities" connectionString="metadata=res://*/LoggingModel.csdl|res://*/LoggingModel.ssdl|res://*/LoggingModel.msl;provider=System.Data.SqlClient;provider connection string="data source=CSTestLSDW;initial catalog=LoanServicingDW;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Related
I have data in a SQLite Database. But I can not be sure that it will always be there. So when I start my Program I first want to check if the SQLite Database exists and when not I want to create one with the DbSet's I already have in my DbContext.
public class MaintenanceDB : DbContext
{
public MaintenanceDB() : base (new SQLiteConnection(new
SQLiteConnectionStringBuilder { DataSource = "data.sqlite"}.ConnectionString), true)
{
}
public DbSet<MaintenanceEntry> MaintenanceEntries { get; set; }
public DbSet<ModuleEntry> ModuleEntries { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MaintenanceEntry>().ToTable("some Table");
modelBuilder.Entity<ModuleEntry>().ToTable("some Table");
}
}
When I delete my SQLite Database and startup my Program again then I want my SQLite Database to be created.
<connectionStrings>
<add name="MaintenanceDB" connectionString="" providerName="System.Data.SqLite" />
</connectionStrings>
public class MaintenanceDB : DbContext
{
public MaintenanceDB() : base ("Name=MaintenanceDB")
And try the solutions below:
var context = new MaintenanceDB();
if (!context.Database.Exists())
context.Database.Create();
Or
var context = new MaintenanceDB();
context.Database.CreateIfNotExists();
Or create an initializer class as below:
// public class ContentInitializer: DropCreateDatabaseAlways <MaintenanceDB>
// public class ContentInitializer: CreateDatabaseIfNotExists <MaintenanceDB>
public class ContentInitializer: DropCreateDatabaseIfModelChanges <MaintenanceDB>
And put this at the beginning of the application.
Database.SetInitializer (new ContentInitializer ());
I want to use the Scaffolding Mechanism in the Entity Framework to create a MusicDBContext database and table automatically, but a problem occurred when I was programming.
The creation of steps shown below:
1. Create a console application.
2. Use the NuGet to install the Entity Framework: PM> install-package Entity Framework
3. Insert the following code into the configuration Session in App.Config:
<connectionStrings>
<add name="MusicDBContext"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;
Initial Catalog=MusicDBContext;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|\MusicDBContext.mdf"
providerName="System.Data.SqlClient" />
</connectionStrings>
4. Write the following code in the console:
using System;
using System.Linq;
using System.Data.Entity;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
try
{
MusicDbContext db = new MusicDbContext();
Music music = new Music { Title = "Far Away From Home",
ReleaseDate = DateTime.Now };
db.Musics.Add(music);
db.SaveChanges();
db.Musics.ToList().ForEach(x => Console.WriteLine($"{x.ID},
{x.Title},{x.ReleaseDate}"));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
if(ex.InnerException != null)
{
Console.WriteLine(ex.InnerException.Message);
}
}
Console.ReadKey();
}
}
public class Music
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { set; get; }
}
public class MusicDbContext : DbContext
{
public MusicDbContext() : base("MusicDBContext") { }
public DbSet<Music> Musics { set; get; }
}
}
However, the following error occurred during runtime:
A file activation error occurred.
The physical file name '\\MusicDBContext.mdf' may be incorrect.
Diagnose and correct additional errors, and retry the operation.
CREATE DATABASE failed. Some file names listed could not be created.
Check related errors.
When I delete all the content in the connectionStrings session, it runs OK.
Entity Framework uses the default connection of SqlLocalDB.
ConnectionString shown below:
Data Source=(localdb)\\mssqllocaldb;Initial Catalog=MusicDBContext;Integrated Security=True;MultipleActiveResultSets=True
Why is there a problem with the connection named MusicDBContext?
The keyword DataDirectory has problem?
Hi I have server with some databases that have the same schema. I use EF6 Database/Model First code and I do not want to create deterrent DbContext for them. for example my generated DbContext is :
public partial class TEST_Rev5_FINALEntities : DbContext
{
public TEST_Rev5_FINALEntities()
: base("name=TEST_Rev5_FINALEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Header> tbl_Headers { get; set; }
public virtual DbSet<Output> tbl_Output { get; set; }
public virtual DbSet<Run> tbl_Run { get; set; }
}
and I created a partial class to set the connection string
public partial class TEST_Rev5_FINALEntities : DbContext
{
public TEST_Rev5_FINALEntities(DbConnection dbConnection)
: base(dbConnection, true)
{
}
}
And I have the following method to create the connection with deterrent connection string:
public DbConnection GetConnectionString()
{
DbConnection conn;
SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder
{
DataSource = DataSource,
IntegratedSecurity = false,
UserID = User,
Password = Password,
MultipleActiveResultSets = true
};
SqlConnectionFactory sqlConnectionFactory = new SqlConnectionFactory(sqlConnectionStringBuilder.ConnectionString);
conn = sqlConnectionFactory.CreateConnection(DatabaseName);
return conn;
}
Finally I try to run it like this:
using (var context = new TEST_Rev5_FINALEntities(_dal.Connector.GetConnectionString()))
{
return context.tbl_Headers.FirstOrDefault();
}
but I get this error :
System.Data.Entity.Infrastructure.UnintentionalCodeFirstException
HResult=0x80131509 Message=The context is being used in Code First
mode with code that was generated from an EDMX file for either
Database First or Model First development.
How can I do it?
The behavior EF uses depends on the way your connection string looks. If it includes a metadata attribute like this:
metadata=res://*/model.csdl|res://*/model.ssdl|res://*/model.msl;
It will presume you are using Database or Model first development.
To make sure Code First is used, remove metadata part of the connection string.
I am getting the error The entity type RelyingParty is not part of the model for the current context even though it exists.
My edmx name is SSO. The edmx is present within Entities folder in Entrada.DAL assembly. Following is the code of SSO.Context class
namespace Entrada.DAL.Entities
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class SSOEntities : DbContext
{
public SSOEntities()
: base("name=SSOEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<KeyValuePair> KeyValuePairs { get; set; }
public virtual DbSet<RelyingParty> RelyingParties { get; set; }
}
Following is the connections string in web.config
<add name="SSOEntities" connectionString="metadata=res://*/Entities.SSO.csdl|res://*/Entities.SSO.ssdl|res://*/Entities.SSO.msl;provider=System.Data.SqlClient;provider connection string="data source=dbname;initial catalog=SSO;persist security info=True;user id=user;password=******;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
This is the code where the error is thrown:
public List<RelyingPartyDALDTO> GetAllRelyingParty()
{
List<RelyingParty> relyingPartDB = DBContext.RelyingParties.ToList();
List<RelyingPartyDALDTO> relyingPartyList = RelyingPartyEntityToDAL.Map<List<RelyingPartyDALDTO>>(relyingPartDB);
return relyingPartyList;
}
DBContext is:
public SSOEntities DBContext
{
get
{
if (SSOEntities == null)
{
SSOEntities = new SSOEntities();
}
return SSOEntities;
}
}
I am getting error on executing the statement:
List relyingPartDB = DBContext.RelyingParties.ToList();
Check the error here
Can you see the error in DBContext? Already existing table(KeyValuePair) does not throw any error but the newly added table RelyingParty throws that error.
I am not understanding what is the problem. For any new table i add to edmx, i am facing this issue.
Can anyone please help me?
Try this in your SSOEntities class
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<RelyingParty>().ToTable("RelyingParty");
}
Good Day,
I understand so far that EF tries to have the developer work in a code-first paradigm. I am having trouble with my setup at the moment because EF wants to Create a database - and it is being denied. I have already created a database and also changed the generated database connection string to where I want it to connect - and which database to use.
I haven't extensively used EF in my career, but I see a growing need for it over the ADO.NET approach. I have decided to try my hand at it. Here is what I have:
Connection String
<add name="DefaultConnection" connectionString="Data Source=EON-PC\2008;Initial Catalog=Experimental;Integrated Security=true;" providerName="System.Data.SqlClient" />
MVC Models
namespace EFExperiment.Models
{
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
[Table("stores")]
public class Stores
{
[Key]
public string Id { get; set; }
public string StoreName { get; set; }
public string AdminEmail { get; set; }
public string Url { get; set; }
}
public class StoreDbContext : DbContext
{
public StoreDbContext()
{
//Database.SetInitializer<StoreDbContext>(null); //Tried this - also failed. It didn't try to create a database here
}
public DbSet<Stores> Stores { get; set; }
}
}
Controller
namespace EFExperiment.Controllers
{
using EFExperiment.Models;
using System.Linq;
using System.Web.Mvc;
public class StoresController : Controller
{
private StoreDbContext db = new StoreDbContext();
public ActionResult Index()
{
return View(db.Stores.ToList());
}
}
}
Error:
CREATE DATABASE permission denied in database 'master'.
What confuses me now is - how do you use EF when it is intended to wipe and recreate your DB? Am I missing something here? I would like to read from my actual tables in my DB, along with other CRUD operations - not have it recreate it every time I run my application.