Missing metadata in connection string error - c#

My first, very basic code related to EF6, option "Empty code first model", throws exception (marked line, below), declaring the lack of metadata keyword in connectionString. What CSDL, MDL, SSDL (metadata) should I set as my model is empty ? What am I missing ?
//Model source file
public class Modelno : DbContext
{
public Modelno(): base("name=Modelno") {}
public virtual DbSet<MainTBL> MainTBLs { get; set; }
}
public class MainTBL
{
public int GlId { get; set; }
public string GlNam { get; set; }
}
//Form source file
private void button1_Click(object sender, EventArgs e)
{
MainTBL gl = new MainTBL();
gl.GlId = 1;
gl.GlNam = "SomeName";
Modelno modal = new Modelno();
modal.MainTBLs.Add(gl); // exception here !
modal.SaveChanges();
}
//App.config file (partially)
<connectionStrings>
<add name="Modelno" connectionString="provider=FirebirdSql.Data.FirebirdClient;provider connection string="data source=localhost;initial catalog=D:\Fb\tab\TEST2.FDB;user id=SYSDBA;password=masterkey"" providerName="System.Data.EntityClient"/>
</connectionStrings>

Related

How should I seed data in Entity Framework 6

I've problem with seeding data to database. Eariler I tried way from this tut: Seed Data in EF 6 Code-First
and then the seed method is never called
DBSchool.cs
namespace SchoolTest.DAL
{
public class DBSchool : DbContext
{
public DBSchool() : base("DBSchool")
{
Database.SetInitializer(new Seeder());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public DbSet<Guest> Guests { get; set; }
}
}
Seeder.cs
public class Seeder : DropCreateDatabaseAlways<DBSchool>
{
protected override void Seed(DBSchool context)
{
IList<Guest> GuestList = new List<Guest>();
GuestList.Add(new Guest()
{
Name = "Dexter",
Surname = "Dexter",
Email = "test#test.com"
});
context.Guests.AddRange(GuestList);
context.SaveChanges();
base.Seed(context);
}
}
Guest.cs
public class Guest
{
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
[Key]
public int GuestId { get; set; }
}
App.config
<appSettings>
<add key="DatabaseInitializerForType SchoolTest.DAL.DBSchool, SchoolTest"
value="SchoolTest.Data.Seeder, SchoolTest" />
</appSettings>
Is there any way to call the Seed() method or just through the Configuration.cs?
Try changing your code like this.
public class DBSchool : DbContext
{
public DBSchool() : base("name=<database-name>")
{
Database.SetInitializer<DBSchool>(new Seeder());
}
// Rest of your implementation
}
Replace <database-name> with the name of your database.
If that didn't work, you can give a Generic Type Parameter to the context class and change your code as follows.
Seeder.cs -> public class Seeder<T> : DropCreateDatabaseAlways<DBSchool>
DBSchool.cs -> Database.SetInitializer<DBSchool>(new Seeder<DBSchool>());
Read more on that here.
If that didn't work either, you can use migrations and seed data using custom sql using Sql().

EF - could not find a model

I have 2 similar DBs. So, both DBs have tables AllowedDates and AllowedTimes (with the same structore). I try to connect to these 2 DBs in my project. I created first model (DB.edmx) for first DB and second model (TEX.edmx) for second DB. Also, I renamed to AllowedDateTex and AllowedTimeTex EntityTypes for TEX.edmx to prevent name conflict of classes. In result, I have error in any case on line:
List<AllowedDateTex> allowedDatesTex = (from i in _dbContextTex.AllowedDateTexes select i).ToList();
Additional information: Could not find the conceptual model type for
'ITW2012Mobile.Models.AllowedDate'.
why it tries to use 'ITW2012Mobile.Models.AllowedDate' and how to fix it?
I use the latest version of EF.
[ADDED]
My connection strings:
<add name="DefaultConnection" connectionString="data source=(local);initial catalog=JSAVIP;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="ITW2012Entities" connectionString="metadata=res://*/Models.DB.csdl|res://*/Models.DB.ssdl|res://*/Models.DB.msl;provider=System.Data.SqlClient;provider connection string="data source=(local);initial catalog=JSAVIP;Integrated Security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="TexEntities" connectionString="metadata=res://*/Models.TEX.csdl|res://*/Models.TEX.ssdl|res://*/Models.TEX.msl;provider=System.Data.SqlClient;provider connection string="data source=(local);initial catalog=fsmf2012;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
call a second model:
TexEntities _dbContextTex;
_dbContextTex = new TexEntities();
var a = (from i in _dbContextTex.AllowedDateTexes select i).ToList();
(on third string I get the error "Additional information: Could not find the conceptual model type for 'ITW2012Mobile.Models.AllowedDate'.")
defined AllowedDateTex etc:
namespace ITW2012Mobile.Models
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class TexEntities : DbContext
{
public TexEntities()
: base("name=TexEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<AllowedDateTex> AllowedDateTexes { get; set; }
public DbSet<AllowedTimeTex> AllowedTimeTexes { get; set; }
}
}
namespace ITW2012Mobile.Models
{
using System;
using System.Collections.Generic;
public partial class AllowedDateTex
{
public AllowedDateTex()
{
this.AllowedTimes = new HashSet<AllowedTimeTex>();
}
public int DayID { get; set; }
public System.DateTime Day { get; set; }
public virtual ICollection<AllowedTimeTex> AllowedTimes { get; set; }
}
}
namespace ITW2012Mobile.Models
{
using System;
using System.Collections.Generic;
public partial class AllowedTimeTex
{
public int TimeID { get; set; }
public int DayID { get; set; }
public int Hour { get; set; }
public int Minute { get; set; }
public virtual AllowedDateTex AllowedDate { get; set; }
}
}
EDIT 2:
I decided to remove EF-models at all and recreate it. When I add first EF-model - all is ok. When I add one more with tables, which have the same names, as in first EF-model then classes from first model are recreated!
Thanks

How to connect to different database using ASP.NET with MVC3

I am new in ASP.NET but developed systems in Qt platform.I want to get data from a different database and use it in my aplication and save it to my database. I am using ASP.NET and C# through MVC3 approach.
I tried it thru:
Having connection strings to different databases in web.config file as follows.
<add name="DBSContext"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\DBS_Example_DB.mdf;Integrated Security=True"
providerName="System.Data.SqlClient"/>
<add name="VIPSContext"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\VIPS.mdf;Integrated Security=True"
providerName="System.Data.SqlClient"/>
Connecting to those two databases in controller as follows
private DBSContext db = new DBSContext();
private VIPSContext vipsdb = new VIPSContext();
Passing data from controller to view[which is successful] and saving it to DB[unsuccessful] through get and post methods
// GET: /Create
public ActionResult Create()
{
//dropdown
ViewBag.CollectorID =new SelectList(db.Collectors, "CollectorID", "FirstName");
//dropdown
ViewBag.TaxpayerID =new SelectList(vipsdb.Taxpayers, "TaxpayerID", "FirstName");
return View();
}
// POST: /Create
public ActionResult Create(Debt_Case debt_case)
{
if (ModelState.IsValid)
{
db.Debt_Cases.Add(debt_case);
db.SaveChanges(); //this is where the error is
return RedirectToAction("Index");
}
return View(debt_case);
}
The error arise when I am saving the changes to the databases.
My model is as follows:
public class Debt_Case
{
public string Debt_CaseID { get; set; }
public string TaxpayerID { get; set; }
public string CollectorID { get; set; }
public string TotalPayment { get; set; }
public virtual Collector Collectors { get; set; }
public virtual Taxpayer Taxpayers { get; set; }
}
}
NB: the navigation properties namely Collectors and Taxpayers are null.
I am getting this error:
An error occurred while updating the entries. See the inner exception
for details.
Can any one help on how to solve this error.

Entity Framework Code First db tables don't generate on existing db

Hi I am using Entity framework code first for the first time and I am having trouble generating the tables.I have created an empty database in my App_Data in an MVC3 application.
This are the models I have created:
public class Brand {
public int BrandId { get;set; }
public string BrandName { get;set; }
}
public class Model
{
public int ModelId { get;set; }
public Brand BrandId { get;set; }
public Category CategoryId { get;set; }
public string ModelName { get;set; }
}
public class Category
{
public int CategoryId { get;set; }
public string CategoryName { get;set; }
}
This is the dbContext:
public class CarsEntities : DbContext{
public DbSet<Brand> Brands { get;set; }
public DbSet<Model> Models { get;set; }
public DbSet<Category> Categories {get;set;}
}
And this is the connectionString in web.config:
<connectionStrings>
<add name="CarsEntities" connectionString="Data Source='D:\Projects IDE\Visual Studio\MyWork\Websites\SellCars\SellCars\App_Data\Cars.sdf'" providerName="System.Data.SqlClient" />
</connectionStrings>
Now I have initialized CarsEntities in my HomeController but it seems that none of the tables get generated.What am I doing wrong?
I think the problem comes in your
webcofig
here is if you want to use the db as a file like mdf file database file
specifically in dtasource
`<add name="CarsEntities" connectionString="data source=.\SQLEXPRESS; Integrated
Security=SSPI;AttachDBFilename=|yourDirectoryDirectory|\thenameofyourdb.mdf;User
Instance=true" providerName="System.Data.SqlClient" /`>
First up - since you're using SQL Server Compact, you need to change the provider name to use Compact rather than SQL Server:
<add name="CarsEntities" connectionString="Data Source='D:\Projects IDE\Visual Studio\MyWork\Websites\SellCars\SellCars\App_Data\Cars.sdf'" providerName="System.Data.SqlServerCe.4.0" />
Next, you'll need to use a database initializer in your Application_Start code somewhere, which tells entity framework whether to create the database tables and how often to recreate them. See here:
http://www.codeguru.com/csharp/article.php/c19999/Understanding-Database-Initializers-in-Entity-Framework-Code-First.htm
http://msdn.microsoft.com/en-us/data/jj591621.aspx

EntityFramework CodeFirst Database doesn't update

One day ago I started using Entity Framework CodeFirst in simple Windows Forms project (C#). I created two models:
[Table("SavesSet")]
public partial class Saves
{
public Saves()
{
this.SkillsSet = new HashSet<Skills>();
}
[Key]
public int SaveID { get; set; }
public string Player { get; set; }
public int Age { get; set; }
public int Money { get; set; }
public virtual ICollection<Skills> SkillsSet { get; set; }
}
[Table("SkillsSet")]
public partial class Skills
{
[Key]
public int SkillID { get; set; }
public string Name { get; set; }
public int Value { get; set; }
public int SavesSaveID { get; set; }
public virtual Saves SavesSet { get; set; }
}
Then I added one row into my database using Visual Studio Database Explorer (local database using SqlServerCe 3.5):
SaveID = 1
Player = "TEST"
Age = 1
Money = 1
I also created form with ListView and wrote some code:
private SavesContext db = new SavesContext();
foreach (Saves s in db.SavesSet.ToList())
{
ListViewItem l = new ListViewItem();
l.Name = s.SaveID.ToString();
l.Text = s.Player;
ListViewSaves.Items.Add(l);
}
But when I started program debugging ListView was empty. I set breakpoint, viewed local variables and saw that SavesSet count was 0.
I added one row via code:
Saves s = new Saves();
s.Player = "TestName";
s.Age = 5110;
s.Money = 200;
db.SavesSet.Add(s);
db.SaveChanges();
And ListView displayed this one. But in my database there was nothing (and its size didn't change). I restarted Visual Studio - and my trouble was still actual: ListView shows item, but database was empty. I checked ConnectionString in App.Config and in VS Database Explorer - they were equal.
So, my question is: How can I explore my real database and where does it stores?
Update.
My DbContext:
public SavesContext()
: base("Saves")
{
}
public DbSet<Saves> SavesSet { get; set; }
public DbSet<Skills> SkillsSet { get; set; }
And my App.Config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="TextSim.Properties.Settings.Saves" connectionString="Data
Source=C:\Documents and Settings\My\My Documents\visual studio
2010\Projects\TextSim\TextSim\Saves.sdf"
providerName="System.Data.SqlServerCe.3.5" />
</connectionStrings>
</configuration>
Entity Framework uses something called Convention over configuration, which means that if you don't supply values for certain things, it uses default values.
If you do not specify your connection string, it will use a default connection string derived from your EF's Namespace and DbContext name. If this is the case, then it would create a new (blank) database using the default system and not use the one you may have configured in Web.Config.
Thus, when you save things, it does save, just to the wrong database.

Categories