why wont my asp.net mvc application seed work properly? - asp.net-mvc

I have the following code to create entities and seed them with data for use in an asp.net mvc application. I am using code first and entity framework. I generate controllers and run the application but on the index.cshtml page my list is empty where the seed data should be.
public class MyContext : DbContext
{
public MyContext() : base("dataDb") {}
public DbSet<Owner> Owners { get; set; }
public DbSet<Pet> Pets { get; set; }
}
public class MyInitializer : DropCreateDatabaseAlways<MyContext>
{
protected override void Seed(MyContext context)
{
// seed database here
context.Owners.AddOrUpdate(
new Owner()
{
//name=,
//id=,
Pets = new List<Pet> { new Pet()
{
//id=,
//name=,
},
new Pet()
{
//id=,
//name=,
}}
},
new Owner()
{
//id=,
//name=,
Pets = new List<Pet> { new Pet()
{
//id=,
//name=,,
}
}
}
);
context.SaveChanges();
}
}
public class Owner
{
public int OwnerId { get; set; }
public string Name { get; set; }
public virtual List<Pet> Pets { get; set; }
}
public class Pet
{
public int PetId { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public virtual Owner Owner { get; set; }
}
}

I found a solution to this problem:
Database.SetInitializer(new MyInitializer()); //important for seed to work
add this line to the context constuctor:
public MyContext() : base("dataDb") {}

You can also add it to your web.config. When it comes to deployment, you can easily remove it from the web.config by using configuration transformer.
<entityFramework>
<contexts>
<context type="MyProject.MyContext, MyProject">
<databaseInitializer type="MyProject.MyInitializer, MyProject" />
</context>
</contexts>
...
</entityFramework>

<connectionStrings>
<add name="MyContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=OwnersPets; AttachDBFilename=|DataDirectory|\OwnersPets.mdf; Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionString>
Example conn string to use with localDb

Related

MVC Database First Failed to set database initializer

I am new to MVC and I have already created Database after we generated the ADO entity data model called HRContextEntities and we created just a bankviewmodel and its Repository and its Index view to display the Database Banks in a List:
Context :
public partial class HRContextEntities : DbContext
{
public HRContextEntities()
: base("name=HRContextEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<ACTIONS> ACTIONS { get; set; }
public virtual DbSet<BANKS> BANKS { get; set; }
public virtual DbSet<EMP_ALAWA> EMP_ALAWA { get; set; }
public virtual DbSet<EMP_CARDS> EMP_CARDS { get; set; }
public virtual DbSet<EMP_DAORA> EMP_DAORA { get; set; }
public virtual DbSet<EMP_DEGREES> EMP_DEGREES { get; set; }
public virtual DbSet<EMP_DEGREES_WORKERS> EMP_DEGREES_WORKERS { get; set; }
public virtual DbSet<EMP_DISSENT> EMP_DISSENT { get; set; }
public virtual DbSet<EMP_EMPLOYEES> EMP_EMPLOYEES { get; set; }
public virtual DbSet<EMP_ENDEMP> EMP_ENDEMP { get; set; }
public virtual DbSet<EMP_ENTEDAB> EMP_ENTEDAB { get; set; }
public virtual DbSet<EMP_EQRAR> EMP_EQRAR { get; set; }
public virtual DbSet<EMP_HASMIAT> EMP_HASMIAT { get; set; }
public virtual DbSet<EMP_HOLIDAYS> EMP_HOLIDAYS { get; set; }
public virtual DbSet<EMP_JOBS> EMP_JOBS { get; set; }
...............................
Bank View Model :
public class BankViewModel
{
public decimal BankID { get; set; }
public string BankName { get; set; }
public string BankSymbol { get; set; }
}
Bank Repository class:
public class BankRepository
{
HRContextEntities db = new HRContextEntities();
public BankViewModel[] GetAll(int? take, int? skip)
{
return db.BANKS.Select(s => new BankViewModel { BankID = s.ID, BankName = s.NAME })
.OrderBy(s => s.BankID).Skip(skip != null ? skip.Value : 0)
.Take(take != null ? take.Value : int.MaxValue).ToArray();
}
}
_Banks Partial View from:
#model IEnumerable<HumanResourceManagement.Models.BankViewModel>
#foreach (var item in Model)
{
<tr class="odd gradeX">
<td>
#item.BankID
</td>
<td>
#item.BankName
</td>
<td>
RYD
</td>
</tr>
}
Exception:
Additional information: Failed to set database initializer of type 'MyProject.Context.Config.ContextInitializer, MyProject.Context' for DbContext type 'App.Context.Default, App.Context' specified in the application configuration. See inner exception for details.
web.config
<contexts>
<context type="App.Context.Default, App.Context">
<databaseInitializer type="MyProject.Context.Config.ContextInitializer, MyProject.Context" />
<!--<databaseInitializer type="MyProject.Context.Config.ContextInitializer, MyProject.Context" />-->
</context>
</contexts>
so what is the solution for this exception
I think your problem lies in your web.config file:
<contexts>
<context type="App.Context.Default, App.Context">
<databaseInitializer type="MyProject.Context.Config.ContextInitializer, MyProject.Context" />
</context>
</contexts>
The context type specifies the fully qualified context class name and the assembly it's in, and the databaseinitializer type specifies the fully qualified name of the initializer class and the assembly it's in. Read this for more info.
Basically, the second param for context type AND databaseinitializer should be the project assembly, not the context. So it should follow this pattern:
<context type=" Blogging.BlogContext, MyAssembly">
<databaseInitializer type="Blogging.MyCustomBlogInitializer, MyAssembly" />
</context>
So in your code, try this (I think your assembly is MyProject):
<contexts>
<context type="MyProject.App.Context, MyProject">
<databaseInitializer type="MyProject.Context.Config.ContextInitializer, MyProject" />
</context>
</contexts>

object reference not set to an instance of an object scaffolding mvc

I have a problem to scaffolding my model.
I get following error "object reference not set to an instance of an object"
My model :
public class Position
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long PositionID { get; set; }
public long OfferID { get; set; }
[Required]
[Display(Name = "Positie omschrijving")]
public string Name { get; set; }
[Required]
public int PositionNr { get; set; }
[Required]
public double WorkingHeight { get; set; }
public long PalletTypeID { get; set; }
public long MotorTypeID { get; set; }
public long Enveriment { get; set; }
}
My DBContext :
public class FlowContext : DbContext
{
public DbSet<Position> Positions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
this.Configuration.LazyLoadingEnabled = true;
//Positie
modelBuilder.Entity<Position>()
.HasKey(j => j.PositionID);
}
}
My connection string in web.config
<connectionStrings>
<add name="FlowContext" connectionString="data source=.\SqlExpress; Integrated Security=True;Initial Catalog=Flow;" providerName="System.Data.SqlClient" />

Create database using code first Entity Framework in SQL Server

I am using code first EF and new to this framework. I am trying to create a database using Database.SetInitializer but it looks like I need SQL Server Express. But I have to create database in SQL Server 2014. How to do this?
Can anybody explain this with the example from EF-dbcontext book which has following classes.
public class BreakAwayContext : DbContext
{
public DbSet<Destination> Destinations { get; set; }
public DbSet<Lodging> Lodgings { get; set; }
public DbSet<Trip> Trips { get; set; }
public DbSet<Person> People { get; set; }
public DbSet<Reservation> Reservations { get; set; }
public DbSet<Payment> Payments { get; set; }
public DbSet<Activity> Activities { get; set; }
}
class Program
{
static void Main(string[] args)
{
Database.SetInitializer(new InitializeBagaDatabaseWithSeedData());
try
{
using (var context = new BreakAwayContext())
{
foreach (var destination in context.Destinations)
Console.WriteLine(destination.Name);
}
}
catch(Exception ex){
Console.WriteLine(ex.ToString());
}
Console.Read();
}
}
public class InitializeBagaDatabaseWithSeedData : DropCreateDatabaseAlways<BreakAwayContext>
{
protected override void Seed(BreakAwayContext context)
{
context.Destinations.Add(new Destination
{
Name = "Hawaii",
Country = "USA",
Description = "Sunshine, beaches and fun."
});
context.Destinations.Add(new Destination
{
Name = "Wine Glass Bay",
Country = "Australia",
Description = "Picturesque sandy beaches."
});
}
Set your connection string in your constructor:
public class BreakAwayContext : DbContext
{
public BreakAwayContext()
: base("MyConnectionString", throwIfV1Schema: false)
{
}
...
Then set your connection string in web.config or app.config:
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=servername;Initial Catalog=dbname;..." providerName="System.Data.SqlClient" />
</connectionStrings>

Retrieve data from sql in MVC 4

Platfrom : MVC4
Hi,
I am new to MVC4 and I am trying to retrieve the data from SQL using Entity framework, but it fails. Here is the code I have tried so far :
Model: MovieListing.cs
[Table("MovieMaster")]
public class MoviesListing
{
public int MovieId { get; set; }
public string Name { get; set; }
public string year { get; set; }
public string Image { get; set; }
public string producer { get; set; }
public string plot { get; set; }
}
Model:
public class MovieContext:DbContext
{
public DbSet<MoviesListing> Movies { get; set; }
}
View :
#model MovieManiac.Models.MoviesListing
#{
ViewBag.Title = "Moviedetails";
}
<h2>Moviedetails</h2>
<table>
<tr>
<td>Movie Name</td>
<td> #Model.Moviename</td>
</tr>
</table>
Controller:
public ActionResult MovieDetails(int id)
{
MovieContext objMovies = new MovieContext();
MoviesListing movie = objMovies.Movies.Single(mov => mov.MovieId == id);
return View(movie);
}
So, in the browser, when I enter the Id, I want to retrieve information from database.I am using local sql db. Any suggestions?
Connection String:
</configSections>
<connectionStrings>
<add name="MovieContext" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MovieManiac-20150318225934;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MovieManiac-20150318225934.mdf" />
</connectionStrings>
error:
An exception of type 'System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: One or more validation errors were detected during model generation:
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'MoviesListing' has no key defined. Define the key for this EntityType.
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'Movies' is based on type 'MoviesListing' that has no keys defined.
You need to add the Key attribute to the I'd property so EF knows what is the primary key
https://msdn.microsoft.com/en-us/data/jj591583.aspx
http://www.entityframeworktutorial.net/code-first/key-dataannotations-attribute-in-code-first.aspx
Update
You may be able to use int and numeric, although I wouldn't bother myself, just change your model to decimal to match the datatype mapping... https://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx... if you have a need to use numeric.
Also decorate your class with the Key attribute
[Table("MovieMaster")]
public class MoviesListing
{
[Key]
public int MovieId { get; set; }
public string Name { get; set; }
public string year { get; set; }
public string Image { get; set; }
public string producer { get; set; }
public string plot { get; set; }
}
You can read about using a decimal (numeric) as a key http://dotnetwindow.blogspot.co.uk/2012/06/using-decimal-as-primary-key-in-entity.html
BTW, are you using code first?
add property to your entity
[Table("MovieMaster")]
public class MoviesListing
{
public int Id { get; set; } // add this
public int MovieId { get; set; }
public string Name { get; set; }
public string year { get; set; }
public string Image { get; set; }
public string producer { get; set; }
public string plot { get; set; }
}
or else use this
public class MovieContext:DbContext
{
public DbSet<MoviesListing> Movies { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MoviesListing>.HasKey(x => x.MovieId );
base.OnModelCreating(modelBuilder);
}
}

Add New Controller to MVC 4

I want to add new controller to my MVC application.Here is my screen
First of all MovieDBContext do not exist in this list,
I created New one. When i press Add button,I get this popup error
Do i need to create Model first? Here is my Model code
`public class LogOn
{
Database db = DatabaseFactory.CreateDatabase("MovieDBContext");
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}`
My web.config has this code
<add name="MovieDBContext" connectionString="Data Source=.\SQLExpress;Initial Catalog=test;User ID = sa; Password = 123456;"
providerName="System.Data.SqlClient" />
I think you should do this:
public class LogOn
{
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
public class LogOnContext : DbContext
{
public LogOnContext() : base("MovieDBContext")
{
}
public DbSet<LogOn> LogOns{ get; set; }
}
Then build project and add a scaffolding item (controller).
You need to change because there's an ambiguous reference:
replace in Edit() method (after controller scaffolding):
db.Entry(logon).State = EntityState.Modified;
with:
db.Entry(logon).State = System.Data.Entity.EntityState.Modified;
Your Edit method should look like as follows:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="Id,UserName,Password")] LogOn logon)
{
if (ModelState.IsValid)
{
db.Entry(logon).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(logon);
}
After you create the model as follows:
public class LogOn
{
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
public class LogOnContext : DbContext
{
public LogOnContext()
: base("MovieDBContext")
{
}
public DbSet<LogOn> LogOns { get; set; }
}
and buil project when you select Data Context class you select (in scaffolding menu)
LogOnContext (MvcFirst.Models) not MvcFirst.Models.DBContext
I had the same problem. I used entity framework version 6. Then I found that it was happening for EF. Because version 6 does not support scaffolding properly with MVC 4. Then I remove it and replace it with version 5. This tricks may be help you. If it helps please give a vote. Thanks

Resources