The argument 'nameOrConnectionString' cannot be null, empty or contain only white space in Entity Framework project - entity-framework-6

I'm getting this error as soon as I try and initialize my DBContext
Short background : I'm using a shared dll which contains DBcontext entity framework with all entites, this is referenced in my project along with enityframework.dll etc.
I can see all the classes within and here is the code in the Model.dll
namespace Model
{
public class BSysDbContext : DbContext
{
public BSysDbContext(bool proxyCreationEnabled = true);
public virtual DbSet<TaskResource> TaskResources { get; set; }
public virtual DbSet<TaskOrder> TaskOrders { get; set; }
public virtual DbSet<TaskMessage> TaskMessages { get; set; }
public virtual DbSet<TaskEvent> TaskEvents { get; set; }
etc
In my code I'm trying to retrieve the data and it gets the above error when hitting this "_context = new BSysDbContext();"
public partial class ChangeSupervisor : DevExpress.XtraEditors.XtraForm
{
BSysDbContext _context;
public ChangeSupervisor()
{
InitializeComponent();
_context = new BSysDbContext();
}
}
My connection string is :
<connectionStrings>
<add name="BSysDbContext" connectionString="metadata=res://Model.dll/BSysDbModel.csdl|
res://Model.dll/BSysDbModel.ssdl|
res://Model.dll/BSysDbModel.msl
;provider=System.Data.SqlClient;provider connection string=';data source=DESKTOP-5T9EDLN;initial catalog=BuilderSysDB_DEV;user id=llduser;password=P#ssw0rd1;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework';" providerName="System.Data.EntityClient" />
</connectionStrings>
No it doesn't matter what I put in the connection string, it doesn't seem to even know the string exists.
According to what I've googled I don;t need to have the model.dll like this
public class BSysDbContext : DbContext
{
public BSysDbContext ()
: base("name=BSysDbContext")
{
}
}
Since the name is the same.
NB, I don't have access to the source of the DLL otherwise I would have made this change.
All I need to know is... Is the missing "public BSysDbContext ()
: base("name=BSysDbContext") " in the DLL what is causing my error message or am I missing something here?
The connection string looks ok to me, I created another blank project and used that as a sample to create this one
Any advice is appreciated

Ok, so after a long trial and error period, the solution (that was obviously not known to me as a newbie to entity framework and migration dll's) was that even though the separate dll which holds the entity models has already got the context and definitions, you also need to have your own dbcontext class in your project with all the tables
public class BSysDbContext : DbContext
{
public BSysDbContext()
: base("Name=BSysDbContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<tblJob>().ToTable("tblJob", "Entity");
modelBuilder.Entity<TaskOrder>().ToTable("TaskOrder", "Entity");
modelBuilder.Entity<Project>().ToTable("Project", "Entity");
modelBuilder.Entity<Order>().ToTable("Order", "Entity");
modelBuilder.Entity<OrderCode>().ToTable("OrderCode", "Entity");
modelBuilder.Entity<ProjectTask>().ToTable("ProjectTask", "Entity");
modelBuilder.Entity<Model.Task>().ToTable("Task", "Entity");
modelBuilder.Entity<tblSupervisor>().ToTable("tblSupervisor", "Entity");
modelBuilder.Entity<tblSupplier>().ToTable("tblSupplier", "Entity");
modelBuilder.Entity<JobProject>().ToTable("JobProject", "Entity");
base.OnModelCreating(modelBuilder);
}
public virtual DbSet<tblJob> Jobs { get; set; }
public virtual DbSet<TaskOrder> TaskOrders { get; set; }
public virtual DbSet<Project> Projects { get; set; }
public virtual DbSet<Order> Orders { get; set; }
etc....

Related

The dbo.ASPNetUser and the other tables like this don't appear in my Server Explorer

I am working in my MVC5 project and I have created a DbContext different to the ApplicationDbContext but it inherits from the same class. I have been developing some parts of my project but now I want to add all the authentication and authorization stuff. But the tables that ASP.NET creates automatically for this purpose don't show up in my Server Explorer although I can work with the sets named Users and Roles of my context. I have searched the reasons of this but I found nothing useful. I hope someone can answer my question and whether it is an important issue or not. I add the code of my DbContext class. Sorry for my English cause I know it is terrible.
namespace GestionPaladares.Models
{
using System;
using System.Data.Entity;
using System.Linq;
using System.Data.Entity.ModelConfiguration.Conventions;
using GestionPaladares.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
public class PaladarContext : IdentityDbContext<ApplicationUser>
{
// Your context has been configured to use a 'CodeFirstDatabaseModel' connection string from your application's
// configuration file (App.config or Web.config). By default, this connection string targets the
// 'GestionPaladares.Models.CodeFirstDatabaseModel' database on your LocalDb instance.
//
// If you wish to target a different database and/or database provider, modify the 'CodeFirstDatabaseModel'
// connection string in the application configuration file.
public PaladarContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
// Add a DbSet for each entity type that you want to include in your model. For more information
// on configuring and using a Code First model, see http://go.microsoft.com/fwlink/?LinkId=390109.
public virtual DbSet<Product> Products { get; set; }
public virtual DbSet<FoodAndDrink> Foods { get; set; }
public virtual DbSet<SoldBill> SoldBills { get; set; }
public virtual DbSet<CostBill> CostBills { get; set; }
public virtual DbSet<Seller> Sellers { get; set; }
public virtual DbSet<Grocer> Grocers { get; set; }
public virtual DbSet<Owner> Owners { get; set; }
public virtual DbSet<Category> Categories { get; set; }
public virtual DbSet<Measure> Measures { get; set; }
public virtual DbSet<Edge> Edges { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
Add ApplicationUser in Dbcontext
public DbSet<ApplicationUser> ApplicationUser { get; set; }
For example,
namespace GestionPaladares.Models
{
using System;
using System.Data.Entity;
using System.Linq;
using System.Data.Entity.ModelConfiguration.Conventions;
using GestionPaladares.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
public class PaladarContext : IdentityDbContext<ApplicationUser>
{
// Your context has been configured to use a 'CodeFirstDatabaseModel' connection string from your application's
// configuration file (App.config or Web.config). By default, this connection string targets the
// 'GestionPaladares.Models.CodeFirstDatabaseModel' database on your LocalDb instance.
//
// If you wish to target a different database and/or database provider, modify the 'CodeFirstDatabaseModel'
// connection string in the application configuration file.
public PaladarContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
// Add a DbSet for each entity type that you want to include in your model. For more information
// on configuring and using a Code First model, see http://go.microsoft.com/fwlink/?LinkId=390109.
public virtual DbSet<Product> Products { get; set; }
public virtual DbSet<FoodAndDrink> Foods { get; set; }
public virtual DbSet<SoldBill> SoldBills { get; set; }
public virtual DbSet<CostBill> CostBills { get; set; }
public virtual DbSet<Seller> Sellers { get; set; }
public virtual DbSet<Grocer> Grocers { get; set; }
public virtual DbSet<Owner> Owners { get; set; }
public virtual DbSet<Category> Categories { get; set; }
public virtual DbSet<Measure> Measures { get; set; }
public virtual DbSet<Edge> Edges { get; set; }
public DbSet<ApplicationUser> ApplicationUser { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
Since you are using EF, you should first add migration, then do update database from the PM console window. Take a note you have to select the correct project form the list and be sure of the right connection string in your code or appsettings file.
Or, you have to create your own method to call on startup for fixing the database for you.
public static void EnsureDatabaseCreated(IConfiguration configuration)
{
using (var context = new DatabaseContext(configuration.GetConnectionString(GlobalConstants.APP_SETTINGS_CONNECTION_NAME)))
{
context.Database.Migrate();
}
}
public Startup(IConfiguration configuration, IHostingEnvironment environment)
{
EnsureDatabaseCreated(this.configuration);
}
Change the DatabaseContext class name with yours.
Hope this helps.

Entity Framework Core Key attribute error to call procedure

I am using ASP.NET Core with Entity Framework Core.
I have a problem with the data model when trying to call a SQL Server procedure.
FromSql method to bind data model is not working if I do not set Key attribute.
This is my code:
Data model class
public class AdminMemberLoginResult
{
public int AdminIndex { get; set; }
public string AdminId { get; set; }
public string AdminName { get; set; }
public bool IsChangePwd { get; set; }
}
DbContext class
public partial class GameContext : DbContext
{
public GameContext()
{
}
public GameContext(DbContextOptions<GameContext> dbContextOption) : base(dbContextOption)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("data base connection string");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
public virtual DbSet<AdminMemberLoginResult> AdminMemberLogin { get; set; }
//public virtual DbSet<DefaultStatisticsResult> DefaultStatistics { get; set; }
}
Snippet of procedure call:
var loginResult = _dbContext.Set<AdminMemberLoginResult>()
.FromSql("exec Game.dbo.sp_admin_getAdminMemberLogin #p_id, #p_pwd",
new SqlParameter("#p_id", id),
new SqlParameter("#p_pwd",pwd)).AsNoTracking().SingleOrDefault();
Key attribute error screenshot:
How can I use FromSql method without Key attribute setting in my data model?
This question is over a year old, but there didn't seem to be a lot of answers out there.
I Just ran across the same issue and I was able to solve this by changing the DbSet to DbQuery in the DbContext.
This is using dot net core 2.1. There are a couple of different approaches that you can read about here: https://msdn.microsoft.com/en-us/magazine/mt847184.aspx

Questions about Metadata

Wanted to get some clarity on something in regards to how we are implementing our Metadata.
Our Breeze Api is not directly tied to SQL Server so we have implemented a custom EFContextProvider and the DbSet below....
public class MetadataDbContext : DbContext
{
public MetadataDbContext()
: base(nameOrConnectionString: "MetadataDb")
{
Database.SetInitializer<MetadataDbContext>(null);
}
public DbSet<Order> Orders { get; set; }
public DbSet<OrderMeter> OrderMeters { get; set; }
public DbSet<OrderDemand> OrderDemand { get; set; }
public DbSet<MeterHistory> MeterHistory { get; set; }
public DbSet<FieldTech> FieldTechs { get; set; }
public DbSet<Dispatcher> Dispatchers { get; set; }
public DbSet<OrderLookupData> LookupData { get; set; }
public DbSet<Organization> Organizations { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<Alert> Alert { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
As you can see I am pointing that DbSet at a database called "MetadataDb" which is just an sdf file we deploy with our project. We then override SaveChangesCore in the Context Provider to route our saves to the correct services instead of going direct to Entity Framework. My question is during some testing we noticed that it seemed Breeze was trying to update the sdf file in some cases. It did not appear that the size of the file changed, but just wanted to make sure before we go to production that the sdf file we are pointing the Metadata at does not grow on our server.
Thanks really enjoy using Breeze.
If the only thing that you are using the .sdf file for is to return metadata then Breeze doesn't do anything more than extract the "edmx" from the ObjectContext or DbContext associated with your database. My guess is that just the act of spinning up the context is causing EF to "modify" the "sdf" file. Breeze is not doing anything to touch the database directly.

Mapping EF 4.1 code-first models to database tables

I have been trying the model-first method when designing my application. We usually like to add a prefix to our tables in larger databases so it is easier to find stuff. For example:
sc_ = Shopping cart tables
wb_ = Water billing tables
ea_ = Employment Application tables
The class I have setup looks like this so far.
public class EFDbContext : DbContext
{
public DbSet<Transaction> Transactions { get; set; }
public DbSet<TransactionItem> TransactionItems { get; set; }
public DbSet<Response> Response { get; set; }
}
Web.config (set currently for local database testing):
<add name="EFDbContext" connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=database" providerName="System.Data.SqlClient"/>
What do I need to change so that the Transaction object gets linked to the sc_Transactions table? I haven't seen in my searching that clarifies this.
As a second question, do I have to manually create my tables?
You can override the OnModelCreating method from DbContext in your EFDbContext class:
public class EFDbContext : DbContext
{
public DbSet<Transaction> Transactions { get; set; }
public DbSet<TransactionItem> TransactionItems { get; set; }
public DbSet<Response> Response { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Transaction>().MapSingleType().ToTable("someTableNameHere");
}
}
See this post for more info.
You can use System.ComponentModel.DataAnnotations like so:
[Table("tblUser")]
public class User
{
public int ID { get; set; }
public string Name { get; set; }
}
Or with EF 4 you can override the OnModelCreating method to map your tables, which is quite powerful thing as you can map and adjust many things at once.
public class MyContext: DbContext
{
DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().MapSingleType().ToTable("tblUser");
}
}
For more info see:
EF4 CF custom database mapping
EF keynotes from the Build2011 event (custom mappings are at about
15 min or so)

Entity Framework Code First, Unit of Work, Repository and shared DbContext

I'm building a web app using EF Code First and ASP.NET MVC. I have following types:
IProblemRepository
EFProblemRepository
ICategoryRepository
EFCategoryRepository
CleanStreets // db context
IUnitOfWork
// etc.
Code snippets :
public interface IUnitOfWork
{
void Save();
}
public class CleanStreets : DbContext, IUnitOfWork
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<Point> Points { get; set; }
public DbSet<Rating> Ratings { get; set; }
public DbSet<Picture> Pictures { get; set; }
public DbSet<Problem> Problems { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(u => u.Comments)
.WithRequired(c => c.User)
.HasForeignKey(c => c.UserID)
.WillCascadeOnDelete(false);
base.OnModelCreating(modelBuilder);
}
public void Save()
{
this.SaveChanges();
}
}
public class EFProblemRepository : IProblemRepository
{
private readonly CleanStreets data;
public EFProblemRepository(CleanStreets data)
{
this.data = data;
}
public void Save(Problem problem)
{
if (problem.ProblemID == 0)
{
data.Problems.Add(problem);
}
data.Save();
}
...
}
At first, I didn't have a UnitOfWork. I created a new context in every repository. But after I wanted to save a Problem (Problem includes Category), using the Save method provided above, I received the following error:
An entity object cannot be referenced by multiple instances of IEntityChangeTracker
I found, on stackoverflow, that the problem is with my db context and the solution was to create a shared context with the unit of work pattern. I tried to do that (as you can see above) but I still get the error. Every time when I want to store a Problem the error pops. Did I implement a "shared" db context right?
Based on the error message, you may need to detach an object from one context to save it in another. You could also construct a new object copied from the first (deep copy necessary here) in order to do that. There is also additional thought required to handle any foreign keys that don't have object reference counterparts.

Resources