DropDownList from Existing DataBase [Asp.Net Core 2.0 MVC Enity Framework] - entity-framework

I hope you can help me I want to bind the DropDownList
and get the data from an existing Database. Visual Studio doesn't show error but when i Run the app it tells me to migrate my DB even though I've already migrated it.
here's my code.
Create.cs
<div class="form-group">
<label asp-for="DomWasAccNo" class="control-label"></label>
<select asp-for="DomWasAccNo"
class="form-control"
asp-items="#(new SelectList(#ViewBag.ListOfConsumer, "AccountNo","AccountNo"))"></select>
<span asp-validation-for="DomWasAccNo" class="text-danger"></span>
</div>
LibCustomers.cs
This part is autogenerated using this CLI command "dotnet ef dbcontext scaffold "Server=192.168.1.28;Database=SBMA_TUBS;User Id=sa;" Microsoft.EntityFrameworkCore.SqlServer -d -o Model -c "CustomerDbContext"
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace WWFS.Models
{
[Table("LIB_CONSUMERS")]
public partial class LibConsumers
{
[Column("account_no")]
[StringLength(15)]
public string AccountNo { get; set; }
[Column("consumer_name")]
[StringLength(255)]
public string ConsumerName { get; set; }
[Column("address")]
[StringLength(255)]
public string Address { get; set; }
}
}
Controller.cs
List<LibConsumers> libConsumers = new List<LibConsumers>();
libConsumers = (from cons in _context.LibConsumers
select cons).ToList();
libConsumers.Insert(0, new LibConsumers { AccountNo = "Select" });
ViewBag.ListOfConsumer = libConsumers;
DomesticWaste.cs
using Microsoft.EntityFrameworkCore;
namespace WWFS.Models
{
public class DomesticWasteDbContext : DbContext
{
public DomesticWasteDbContext(DbContextOptions<DomesticWasteDbContext> options)
: base(options)
{
}
public DbSet<WWFS.Models.DomesticWaste> DomesticWastes { get; set; }
public DbSet<WWFS.Models.Location> Locations { get; set;}
public DbSet<WWFS.Models.Contractor> Contractors { get; set; }
public DbSet<WWFS.Models.LibConsumers> LibConsumers { get; set; }
}
}
CustomerDbContext.cs
This part is autogenerated using this CLI command "dotnet ef dbcontext scaffold "Server=192.168.1.28;Database=SBMA_TUBS;User Id=sa;" Microsoft.EntityFrameworkCore.SqlServer -d -o Model -c "CustomerDbContext"
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace WWFS.Models
{
public partial class CustomerDbContext : DbContext
{
public virtual DbSet<LibConsumers> LibConsumers { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(#"Server=192.168.1.28;Database=SBMA_TUBS;User Id=sa;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<LibConsumers>(entity =>
{
entity.Property(e => e.AccountNo).ValueGeneratedNever();
entity.Property(e => e.ConsumerName).ValueGeneratedNever();
entity.Property(e => e.Address).ValueGeneratedNever();
});
}
}
}

i think no one can answer this question.

Related

ASP.NET EF with class library

I created a class library which is going to have my database model with DB first approach. I am using the Northwind database.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<NorthwindContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("NorthwindContext"));
});
}
In this method in asp.net project it tells me that the NorthwindContext is not convertible to DBcontext but the class inherits from it:
Error CS0311
The type 'NorthwindDal.NorthwindContext' cannot be used as type parameter 'TContext' in the generic type or method 'EntityFrameworkServiceCollectionExtensions.AddDbContext(IServiceCollection, Action?, ServiceLifetime, ServiceLifetime)'.
There is no implicit reference conversion from 'NorthwindDal.NorthwindContext' to 'Microsoft.EntityFrameworkCore.DbContext'.
If I don't use the AddDbcontext and try to run the project, it just tells me that it cannot find the connection string for the database.
The context is auto created and it inherits from the DBcontext as well.
I think its probably because I try to use the class library to do this but is there a way to use class library with ASP.NET?
Northwind Context
public partial class NorthwindContext : DbContext
{
public NorthwindContext()
: base("name=NorthwindContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Category> Categories { get; set; }
public virtual DbSet<CustomerDemographic> CustomerDemographics { get; set; }
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Order_Detail> Order_Details { get; set; }
public virtual DbSet<Order> Orders { get; set; }
public virtual DbSet<Product> Products { get; set; }
public virtual DbSet<Region> Regions { get; set; }
public virtual DbSet<Shipper> Shippers { get; set; }
public virtual DbSet<Supplier> Suppliers { get; set; }
public virtual DbSet<Territory> Territories { get; set; }
}
Based on your scenario if you would like to implement "database first approach" you could follow the below steps.
Database Schema:
You can download Northwind database schema from our official site as well. Just for reference.
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
Note: You can set any meaningful connection string name here in DefaultConnection as I have set this.
DbContext class:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Categories> Categories { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Categories>().ToTable("Categories");
}
}
appsettings.json:
"ConnectionStrings": {
"DefaultConnection": "Server=YourServerName;Database=Northwind;Trusted_Connection=True;MultipleActiveResultSets=true"
}
Controller:
public class NorthwindController : Controller
{
private readonly MvcAttendanceDbContext _context;
private IHostingEnvironment _hostEnvironment;
public NorthwindController(IHostingEnvironment _environment, MvcAttendanceDbContext context)
{
_hostEnvironment = _environment;
_context = context;
}
public IActionResult Index()
{
var categories = _context.Categories.ToList();
return View(categories);
}
}
View:
#model IEnumerable<MVCApps.Models.Categories>
<h3 class="card-title"><strong>Northwind Category</strong> </h3>
<div class="row">
#foreach (var item in Model)
{
<div class="col-sm-4">
<div class="card" style="width: 18rem;border:1px;padding: 2px 2px 2px 2px; margin-bottom:20px;box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;">
<div class="card-body">
<h5 class="card-title"><strong>#Html.DisplayFor(modelItem => item.CategoryName)</strong> </h5>
<p class="card-text">#Html.DisplayFor(modelItem => item.Description)</p>
<a asp-action="Details" class="btn btn-primary" asp-route-memberId="#item.Description">Details</a> | <a asp-action="EditMember" class="btn btn-warning" asp-route-memberId="#item.CategoryID">Edit</a>
</div>
</div>
</div>
}
</div>
Output:
To generate model classes and database context from an existing database you need to use ef tool scaffolding. You can do it using the command
dotnet ef dbcontext scaffold "Your connection string" Microsoft.EntityFrameworkCore.SqlServer
You need the add reference following NuGet packages if you need to run the command.
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Invalid column name when using Entity Framework Core Table Per Hierarchy Inheritance

I am new to EF Core and am trying to use TPH Inheritance with Entity Framework Core
I have the following classes defined
public class WorkItem {
public Guid Id { get; set; }
public string WorkItemType { get; set; }
public string Description { get; set; }
}
public class Job : WorkItem {
public string BillingNotes { get; set; }
}
In my context, I have
public class JobContextNew : DbContext {
public virtual DbSet<WorkItem> WorkItem { get; set; }
public virtual DbSet<Job> Job { get; set; }
public JobContextNew(DbContextOptions<JobContextNew> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.Entity<WorkItem>(entity => entity.Property(e => e.Id).ValueGeneratedNever());
modelBuilder.Entity<WorkItem>()
.HasDiscriminator(workitem => workitem.WorkItemType)
.HasValue<Job>(nameof(Job));
}
}
If I omit the field in Job, it will pull the data just fine but when I add the BillngNotes back in I get the following error: Invalid column name 'BillingNotes
Can anyone tell me what I might be doing wrong?

Invalid Object Name error when creating database with EF Code First

Hello i am developing a database using EF Core Code First.I keep getting this error when generating the database :
Microsoft.EntityFrameworkCore.DbUpdateException: 'An error occurred
while updating the entries. See the inner exception for details.'
InnerException {"Invalid object name 'Parents'."} System.Exception {Microsoft.Data.SqlClient.SqlException}
From what i have read it seems i can not create the database because the tables are somehow pluralized.
I have searched for solutions including this SO thread and tried the solutions to no avail. The one that i have not tried is the RemovePluralization method because
I do not have this Conventions field in my ModelBuilder and i can not find the package containing it.
Context and Models
public class Parent {
public int ID { get; set; }
public string Name { get; set; }
public ICollection<Child> Children { get; set; }
public Parent() {
this.Children = new List<Child>();
}
}
public class Child {
public int ID { get; set; }
public string Name { get; set; }
public Parent Parent { get; set; }
public int ParentId { get; set; }
}
public class MyContext : DbContext {
public virtual DbSet<Parent> Parents { get; set; }
public virtual DbSet<Child> Children { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Child>()
.HasKey(x => x.ID);
modelBuilder.Entity<Parent>()
.HasKey(x => x.ID);
modelBuilder.Entity<Parent>()
.HasMany(x => x.Children)
.WithOne(k=>k.Parent)
.HasForeignKey(t => t.ParentId);
}
public MyContext(DbContextOptions options):base(options) {
this.Database.EnsureCreated();
this.Database.Migrate(); //i have tried this too
}
}
Usage
var optionsBuilder = new DbContextOptionsBuilder<MyContext>();
optionsBuilder.UseSqlServer(connectionString);
MyContext context = new MyContext(optionsBuilder.Options);
Parent parent = new Parent() { Name = "Parentino" };
context.Parents.Add(parent);
await context.SaveChangesAsync(); //crashes with before mentioned error
I have also tried to set the table names in my OnModelCreating overload this:
modelBuilder.Entity<Parent>().ToTable("parent");
or directly with [Table("name")] attribute over my Model classes to no avail.
Could someone help me out and tell me why i can't generate the database ?
Works fine for me
program.sc
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static async Task Main(string[] args)
{
string connectionString = "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
var optionsBuilder = new DbContextOptionsBuilder<MyContext>();
optionsBuilder.UseSqlServer(connectionString);
MyContext context = new MyContext(optionsBuilder.Options);
Parent parent = new Parent() { Name = "Parentino" };
context.Parents.Add(parent);
await context.SaveChangesAsync(); //crashes with before mentioned error }
}
}
public class Parent
{
public int ID { get; set; }
public string Name { get; set; }
public ICollection<Child> Children { get; set; }
public Parent()
{
this.Children = new List<Child>();
}
}
public class Child
{
public int ID { get; set; }
public string Name { get; set; }
public Parent Parent { get; set; }
public int ParentId { get; set; }
}
public class MyContext : DbContext
{
public virtual DbSet<Parent> Parents { get; set; }
public virtual DbSet<Child> Children { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Child>()
.HasKey(x => x.ID);
modelBuilder.Entity<Parent>()
.HasKey(x => x.ID);
modelBuilder.Entity<Parent>()
.HasMany(x => x.Children)
.WithOne(k => k.Parent)
.HasForeignKey(t => t.ParentId);
}
public MyContext(DbContextOptions options) : base(options)
{
this.Database.EnsureCreated();
this.Database.Migrate(); //i have tried this too
}
}
}
ConsoleApp1.csproj
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>

Why am I receiving errors when using views and controllers created via scaffolding with MVC 5 / EF 6 (inheritance) derived classes?

Why am I receiving errors when using views and controllers created via scaffolding with MVC 5 / EF 6 (inheritance) derived classes?
My background: I am a previous Powerbuilder (client/server programmer) that is endeavoring to learn web-based programming.
I chose ASP.NET and purchased an MSDN license to use Visual Studio 2013 and have been learning by books, online training and plain old hacking on the computer.
The best test is to create some sample application and so here I am. I am learning the MVC and Code First EF because there is so much good info and samples to be had.
However, I am stuck on my inheritance example.
I have 3 classes: AircrewMember derived from Airman derived from Person. They compile without error.
I have a class DbInitializer so "Code First" will create the database. I actually use SQL scripts to load my test data.
I have a class StanEvalDb for the database context info.
I have included pertinent information from web.config.
The problem:
When I use scaffolding to create a controller and views based off of the Airman class (derived from Person), the result returns with errors.
Airman airman = db.People.Find(id);
Error 1
Cannot implicitly convert type 'SEMX1.Entities.Person' to 'SEMX1.Entities.Airman'. An explicit conversion exists (are you missing a cast?)
D:\Projects\VC2013\2015\06-Jun\SEMX1\SEMX1.Web\Controllers\AirmenController.cs 31 29 SEMX1.Web
I think I understand the Table per Hierarchy (TPH) and that physically only one table (People) is created to house all "3" tables.
I am at a loss... I have googled and read many articles but I have no idea how to proceed. Has anyone seen this or tried this?
I assume I am overlooking something simple but I am out of ideas. Any help would be appreciated!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SEMX1.Entities
{
public class Person
{
public virtual int PersonId { get; set; }
[DisplayName("First Name* ")]
[StringLength(40)]
[Required(ErrorMessage = "The First Name field is required.")]
public virtual string PersonFirstName { get; set; }
[DisplayName("Middle Initial ")]
[StringLength(2)]
public virtual string PersonMidInit { get; set; }
[DisplayName("Last Name* ")]
[StringLength(50)]
[Required(ErrorMessage = "The Last Name field is required.")]
public virtual string PersonLastName { get; set; }
[DisplayName("SSN* ")]
[StringLength(11)]
[Required(ErrorMessage = "The SSN field is required.")]
public virtual string PersonSSN { get; set; }
[DisplayName("DOB* ")]
[Required(ErrorMessage = "The DOB field is required.")]
public virtual DateTime? PersonDOB { get; set; }
public virtual int CivilRankId { get; set; }
//public virtual int LifeEventId { get; set; }
public virtual ICollection<LifeEvent> LifeEvents { get; set; }
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SEMX1.Entities
{
public class Airman : Person
{
public virtual int MilitaryRankId { get; set; }
public virtual int MilitaryUnitId { get; set; }
public virtual int AfscId { get; set; }
public virtual ICollection<CareerEvent> CareerEvents { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SEMX1.Entities
{
public class AircrewMember : Airman
{
public virtual int AviationTypeId { get; set; }
public virtual int AirMissionId { get; set; }
public virtual int AircraftId { get; set; }
public virtual int CrewPositionId { get; set; }
public virtual int ExperienceRatingId { get; set; }
public virtual int AirmanshipId { get; set; }
public virtual int TacticalDayRatingId { get; set; }
public virtual int TacticalNightRatingId { get; set; }
public virtual ICollection<AircrewEvent> AircrewEvents { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using SEMX1.Entities;
using System.IO;
namespace SEMX1.Web.DataContexts
{
public class DbInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<StanEvalDb>
{
protected override void Seed(StanEvalDb context)
{
base.Seed(context);
// using SQL scripts to load database with test data
// easier way to get around identity key field problems
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using SEMX1.Entities;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace SEMX1.Web.DataContexts
{
public class StanEvalDb : DbContext
{
public StanEvalDb() : base("StanEvalContext")
{
Database.SetInitializer<StanEvalDb>(new DbInitializer());
}
public DbSet<Person> People { get; set; }
public DbSet<LifeEvent> LifeEvents { get; set; }
public DbSet<CivilRank> CivilRanks { get; set; }
public DbSet<MilitaryRank> MilitaryRanks { get; set; }
public DbSet<MilitaryUnit> MilitaryUnits { get; set; }
public DbSet<MilUnitType> MilUnitTypes { get; set; }
public DbSet<AFSC> AFSCList { get; set; }
public DbSet<CareerEvent> CareerEvents { get; set; }
public DbSet<Airman> Airmen { get; set; }
public DbSet<AviationType> AviationTypes { get; set; }
public DbSet<AirMission> AirMissions { get; set; }
public DbSet<Aircraft> AircraftList { get; set; }
public DbSet<CrewPosition> CrewPositions { get; set; }
public DbSet<ExperienceRating> ExperienceRatings { get; set; }
public DbSet<Airmanship> AirmanshipList { get; set; }
public DbSet<TacticalDayRating> TacticalDayRatings { get; set; }
public DbSet<TacticalNightRating> TacticalNightRatings { get; set; }
public DbSet<AircrewEvent> AircrewEvents { get; set; }
public DbSet<AircrewMember> Aircrew { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//modelBuilder.Entity<Person>()
// .HasMany(p => p.LifeEvents).WithMany(l => l.People)
// .Map(t => t.MapLeftKey("PersonID")
// .MapRightKey("LifeEventID")
// .ToTable("LifeEventPersons"));
//modelBuilder.Entity<Airman>()
// .HasMany(a => a.CareerEvents).WithMany(c => c.Airmen)
// .Map(t => t.MapLeftKey("PersonID")
// .MapRightKey("CareerEventID")
// .ToTable("CareerEventAirmen"));
//modelBuilder.Entity<AircrewMember>()
// .HasMany(a => a.AircrewEvents).WithMany(c => c.Aircrew)
// .Map(t => t.MapLeftKey("PersonID")
// .MapRightKey("AircrewEventID")
// .ToTable("AircrewEventAircrew"));
}
}
}
Web.config (Pertinent Information)
<configuration>
<configSections>
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</configSections>
<connectionStrings>
<add name="StanEvalContext"
connectionString="Data Source=REDCARBOSS2-LAP\RCB2SRV2012;Initial Catalog=DB_25213_SEMX1;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"
providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient"
type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using SEMX1.Entities;
using SEMX1.Web.DataContexts;
namespace SEMX1.Web.Controllers
{
public class AirmenController : Controller
{
private StanEvalDb db = new StanEvalDb();
// GET: Airmen
public ActionResult Index()
{
return View(db.People.ToList());
}
// GET: Airmen/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Airman airman = db.People.Find(id);
if (airman == null)
{
return HttpNotFound();
}
return View(airman);
}
// GET: Airmen/Create
public ActionResult Create()
{
return View();
}
// POST: Airmen/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "PersonId,PersonFirstName,PersonMidInit,PersonLastName,PersonSSN,PersonDOB,CivilRankId,MilitaryRankId,MilitaryUnitId,AfscId")] Airman airman)
{
if (ModelState.IsValid)
{
db.People.Add(airman);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(airman);
}
// GET: Airmen/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Airman airman = db.People.Find(id);
if (airman == null)
{
return HttpNotFound();
}
return View(airman);
}
// POST: Airmen/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "PersonId,PersonFirstName,PersonMidInit,PersonLastName,PersonSSN,PersonDOB,CivilRankId,MilitaryRankId,MilitaryUnitId,AfscId")] Airman airman)
{
if (ModelState.IsValid)
{
db.Entry(airman).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(airman);
}
// GET: Airmen/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Airman airman = db.People.Find(id);
if (airman == null)
{
return HttpNotFound();
}
return View(airman);
}
// POST: Airmen/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Airman airman = db.People.Find(id);
db.People.Remove(airman);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
The error says that it cannot implicitly cast and is asking you to explicitly cast. Try replacing this:
Airman airman = db.People.Find(id);
With:
Airman airman = (Airman)db.People.Find(id);

producing .sdf file using DBContext class?

I am follwoing this tutorial from
http://www.asp.net/entity-framework/tutorials/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
No I have created this code:
using MvcApp2.Models;
using System.Data.Entity.Design.PluralizationServices;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MvcApp2.Models
{
public class StudentContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
and in my Web.config I have added this Connection string:
<add name="StudentContext" connectionString="Data Source=|DataDirectory|Student.sdf" providerName="System.Data.SqlServerCe.4.0"/>
When I build my project,according to the tutorial, I should be expecting an SDF file in my appcode callded students