producing .sdf file using DBContext class? - asp.net-mvc-2

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

Related

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?

Entity Framework is not creating the database

I am trying to create a code first database creation. I have 2 connection strings:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=DESKTOP-1111\SERVER_2014; database=the_userdb;user=sa; password=myPassword" providerName="System.Data.SqlClient" />
<add name="PmisDatabaseContext" connectionString="Data Source=DESKTOP-1111\SERVER_2014; database=the_database;user=sa; password=myPassword" providerName="System.Data.SqlClient" />
</connectionStrings>
At first, I was able to add a migration using this:
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public bool IsActivated { get; set; }
public DateTime EnrollDate { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{ }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//AspNetUsers -> User
modelBuilder.Entity<ApplicationUser>()
.ToTable("User");
//AspNetRoles -> Role
modelBuilder.Entity<IdentityRole>()
.ToTable("Role");
//AspNetUserRoles -> UserRole
modelBuilder.Entity<IdentityUserRole>()
.ToTable("UserRole");
//AspNetUserClaims -> UserClaim
modelBuilder.Entity<IdentityUserClaim>()
.ToTable("UserClaim");
//AspNetUserLogins -> UserLogin
modelBuilder.Entity<IdentityUserLogin>()
.ToTable("UserLogin");
}
}
then I 'enabled migrations' then 'add-migration InitialDatabase' then 'update-database' and was able to successfully created a new database with the tables for logging in.
Now I want to create a new database with a table named ImageLibraries so I did this in my model:
[Table("ImageLibrary")]
public class ImageLibrary
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
[Required]
public string UserId { get; set; }
}
then added:
public class PmisDatabaseContext : DbContext
{
public PmisDatabaseContext()
: base("name=PmisDatabaseContext")
{
Database.SetInitializer<PmisDatabaseContext>(new CreateDatabaseIfNotExists<PmisDatabaseContext>());
}
public virtual DbSet<ImageLibrary> ImageLibraries { get; set; }
}
When I try to 'add-migration AddedImageLibrary', in my migrations folder, I get the 'up()' and 'down()' without anything in it. It's not creating the new database and table. Can you please show me how to do this right. Thank you.

Entity Framework table creation

I have a model which looks like below
public class Employee
{
public int Id { get; set; }
public string Email { get; set; }
public string Forename { get; set; }
}
And I have an configuration file as below
public class EmmployeeConfiguration : EntityTypeConfiguration<Employee>
{
public EmmployeeConfiguration()
{
Property(e => e.Forename).IsRequired();
}
}
And I want it to create a table with Name of HR.Employee (HR being the schema). So, in my DbContext, I added the following.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Employee>().ToTable("Employee", schemaName: "HR");
modelBuilder.Configurations.Add(new EmmployeeConfiguration());
//base.OnModelCreating(modelBuilder);
}
I am expecting the database name to be "HR.Employee", but instead when i run "Enable-Migration", it is always trying to create "dbo.Employees".
Can someone point me what I am missing?

EF Code First, not generating database

I have an console application project in visual 2012. I want to use Entity Framework 6 code-first. when I run my project it does not create any database in my SQL Server. I am not able to create database by code first in my SQL Server.I am not getting any exception while build & run.
below is my code :
namespace CodeFirstNewDBeSample
{
class Program
{
static void Main(string[] args)
{
using (var db = new BlogContext())
{
//Console.Write("Enter a name for new Blog:");
//var name = Console.ReadLine();
//var blog = new Blog { Name = name };
//db.Blogs.Add(blog);
//db.SaveChanges();
}
}
}
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public virtual IEnumerable<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
public class BlogContext : DbContext
{
public BlogContext() : base("name=BlogDBString") { }
DbSet<Blog> Blogs { get; set; }
DbSet<Post> Posts { get; set; }
}
}
Config File :
<connectionStrings>
<add name="BlogDBString" connectionString="data source=MY-PC;initial catalog=BlogDB;integrated security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

Web api Odata error when scaffolding

I've tried to scaffold Odata controller for this entity:
#region Attributes
public Guid TreningId { get; set; }
public DateTime DateTimeWhenTreningCreated { get; set; }
#endregion
#region Navigational properties
public string UserId { get; set; }
public User User { get; set; }
public int RoutineId { get; set; }
public Routine Routine { get; set; }
#endregion
And scaffolding went fine, I'm also using ASP.net Identity, but my user class and database context are defined in another project like this:
public class User : IdentityUser
{
public String Something { get; set; }
}
And database context looks like this:
public class DatabaseContext : IdentityDbContext<User>
{
public MadBarzDatabaseContext()
: base("DefaultConnection")
{
Configuration.LazyLoadingEnabled = true;
}
...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUser>()
.ToTable("Users");
modelBuilder.Entity<User>()
.ToTable("Users");
}
}
Note: I don't have anywhere line:
public DbSet<User> Users{ get; set; }
So after scaffolding my Web api project added this line to my class DatabaseContext:
public DbSet<User> IdentityUsers { get; set; }
But then when I tried to fetch anything from database I got error:
Multiple object sets per type are not supported. The object sets 'IdentityUsers' and 'Users' can both contain instances of type 'Domain.Model.UserAggregate.User'.
If I delete that line I get error:
An exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll but was not handled in user code
Additional information: Could not load file or assembly 'System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
At line (in my WebApiConfig)
config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
If remove lines (from my WebApiConfig):
builder.EntitySet<Trening>("Trening");
builder.EntitySet<User>("IdentityUsers");
Everything forks fine again. So probably problem is whit my User entity, so how can I solve this ? (when I scaffold anything that has nothing to do with User, everything is fine)
EDIT
I've also deleted these lines from my trening controller:
// GET odata/Trening(5)/User
[Queryable]
public SingleResult<User> GetUser([FromODataUri] Guid key)
{
return SingleResult.Create(db.Trenings.Where(m => m.TreningId == key).Select(m => m.User));
}
And added these lines to WebApiConfig:
trenings.EntityType.Ignore(t => t.User);
trenings.EntityType.Ignore(t => t.UserId);
But it didn't help.
EDIT 2
So I've decided to make new test project and I've followed these tutorials (all of them are basically same):
Tutorial 1
Tutorial 2
Tutorial 3
Tutorial 4
So I've extended Identity User using Application user class and added test model like this:
public class TestModel
{
public int Id { get; set; }
public string Test { get; set; }
public string UserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
}
And here is whole IdentityModels class:
namespace WebApplication2.Models
{
public class ApplicationUser : IdentityUser
{
public string Email { get; set; }
public string Data { get; set; }
public ICollection<TestModel> TestModels { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public DbSet<TestModel> TestModels { get; set; }
}
}
And the error remains the same,
I've tried to replace ApplicationUser with IdentityUser in test model and I've added this line:
public DbSet ApplicationUsers { get; set; }
But still same error.
Note: this time I scaffolded Odata controller with TestModel.
Havent seen this error before. According to your errormessage, it looks like these lines are causing your troubles:
modelBuilder.Entity<IdentityUser>()
.ToTable("Users");
modelBuilder.Entity<User>()
.ToTable("Users");