How to connect to different database using ASP.NET with MVC3 - c#

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.

Related

Trying to create application using asp.net mvc with entity framework,but returns zero record

I am trying to learn asp.net mvc by doing hands-on. So i started with very small web application using asp.net mvc along with entity framework to access sql server.
I created one table in sql server localdb
USE Ourlifestory ;
GO
create table staticlocations(
LocationID int primary key,
LocationName varchar(30),
Tripdate datetime,
Locationimage image)
Below is the connection string
<add name="OurLifeStoryDBContext" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\v11.0; Initial Catalog=Ourlifesotry; Integrated Security=True;" />
DBContext class :
public class OurLifeStoryDBContext : DbContext
{
public OurLifeStoryDBContext()
: base("name=OurLifeStoryDBContext")
{
}
public DbSet<StaticLocations> Location { get; set; }
}
Model class for one table :
[Table("staticlocations")]
public class StaticLocations
{
[Key]
[Column(Order = 1)]
public int LocationID { get; set; }
[Column(Order = 2)]
public string LocationName { get; set; }
[Column(Order = 3)]
public DateTime Tripdate { get; set; }
//[Column(TypeName="image")]
//public byte[] LocationImage { get; set; }
}
Controller action method accessing this dbcontext :
public ActionResult GetLocationDetails(int locationID)
{
var dbContext = new OurLifeStoryDBContext();
var location = dbContext.Location.ToList();
return View("_GetLocationDetails");
}
But in above action method on the below line ,
var location = dbContext.Location.ToList();
i am getting zero records though i am very i have one record which i manually inserted through insert statement in database.
Any thoughts what i am missing here?
Here is why nothing was returned, there was a typo in your connection string:
Initial Catalog=Ourlifesotry;
in your connection string should be
Initial Catalog=Ourlifestory;
Why did it not give any "error" or indication?
That's because Entity Framework cannot detect if you spelled your database name wrong. For all it knows, your database could be called "misssssspelled".
Also, when there is no existing database with the provided name, instead of an error value/warning, it will simply return nothing instead.

Windows Forms Entity Framework database solution

I'm currently creating a Windows Forms Application. I require a local database and have opted to use the code-first approach with the Entity Framework in order to build it. I have not worked with a database with C# before and I am struggling to set one up with the entity framework.
I currently have two classes: Ingredient, and Recipe. Both contain POCOs. From what I can gather, the entity framework should create a local database, making these classes tables. However a database is not being created.
Could anyone shed some light on what I am doing wrong? I apologise if my question is too broad.
Thank you for your time.
Ingredient Class:
public class Ingredient
{
public int IngredientID { get; set; }
public string IngredientName { get; set; }
public string IngredientDescription { get; set; }
public virtual Recipe Recipe { get; set; }
}
Recipe Class:
public class Recipe
{
public int RecipeID { get; set; }
public string RecipeName { get; set; }
public string RecpeDescription { get; set; }
public virtual List<Ingredient> Ingredients { get; set; }
public Recipe()
{
this.Ingredients = new List<Ingredient>();
}
}
DbContext Class
class RecipeContext : DbContext
{
public DbSet<Recipe> Recipes { get; set; }
public DbSet<Ingredient> Ingredients { get; set; }
}
EF is quite flexible with these things. Get acquainted with the Nuget Package Manager Console (it is from there that you'll interact with Entity Framework DB generation routines). Following these steps you should be good to go:
Add a connection string to your start up application. An example is the following:
<configuration>
<connectionStrings>
<add name="Local"
connectionString=
"Data Source=.;Initial Catalog=NAME;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Create a Context class that inherits DbContex;
Add the following constructor to you Context class:
public Context() : base("Local") {}
Add DbSet properties to your Context class (so EF can track them down);
Go to the Package Manager Console, select the project that holds the DbContext class, and type the following:
Enable-Migrations
On the same console type:
Add-Migration Initial
Again in the same console:
Update-Database
This should create a database with the name you have set in the connection string.
Hope this helps!
Cheers!
You need a connection string and one of database initializers that create a database if it doesn't exists.
public class RecipeContext : DbContext
{
// the default constructor
public RecipeContext() : base() { }
// this one lets you pass a connection string
public RecipeContext( string connectionString ) : base( connectionString ) { }
...
Then, at the very beginning of your app set the initializer:
Database.SetInitializer<RecipeContext>(new CreateDatabaseIfNotExists<RecipeContext>());
And finally, just try to connect to your database, with a valid connection string:
// local database connection string has to point to the local db server
string cs = "server=(localdb)/v11.0;database=anewdatabase;integrated security=true";
using ( var ctx = new RecipeContext( cs ) )
{
// any database operation will first trigger the initializer
// which initializes the database once per app domain
// in case of the CreateDatabaseIfNotExists
// a new, empty database matching your model is created
}

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

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