In EntityFramwork 6.2.0 I want to create shadow property (is EF 6 Support Shadow Property) - entity-framework-6

My Entity Is
class Student
{
public long Id{ get; set; }
}
DB Context is
public class StudentContext:DbContext
{
public StudentContext():base("name=cnName") {}
public DbSet<Student> Student{ get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>().Property<DateTime>
("CreatedOn");
base.OnModelCreating(modelBuilder);
}
}
The exception is
syntax error cannot convert from string to System.Linq.Expressions.Expression
on below line
modelBuilder.Entity<Student>().Property<DateTime>("CreatedOn");
What I did wrong is entity 6 support shadow property.

Related

How to migrate the ApplicationDbContext to the existing DbContext in ASP.NET MVC EF code-first project?

I followed the ASP.NET MVC tutorial to build the ASP.NET MVC project with EF code-first.
I've created the SchoolContext and use EF code-first to create the Database for my current project.
public class SchoolContext:DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
{
}
public DbSet<Course> Courses { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Student> Students { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Instructor> Instructors { get; set; }
public DbSet<OfficeAssignment> OfficeAssignments { get; set; }
public DbSet<CourseAssignment> CourseAssignments { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Course>().ToTable("Course");
modelBuilder.Entity<Enrollment>().ToTable("Enrollment");
modelBuilder.Entity<Student>().ToTable("Student");
modelBuilder.Entity<Department>().ToTable("Department");
modelBuilder.Entity<Instructor>().ToTable("Instructor");
modelBuilder.Entity<OfficeAssignment>().ToTable("OfficeAssignment");
modelBuilder.Entity<CourseAssignment>().ToTable("CourseAssignment");
modelBuilder.Entity<CourseAssignment>()
.HasKey(c => new { c.CourseID, c.InstructorID });
}
}
Now I want to add the Authorization function to this project using ASP.NET Identity.
I notice that I have the ApplicationDbContext inside my project, how can I migrate the ApplicationDbContext to my existing SchoolContext? Or I need to create another database for the ApplicationDbContext?
Inherit SchoolContext from IdentityDbContext<ApplicationUser> then add aspnet identity tables to modelBuilder:
public class SchoolContext:IdentityDbContext<ApplicationUser>
{ ...
and OnModelCreating method changes like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUser>()
.ToTable("dbo.AspNetUsers");
modelBuilder.Entity<ApplicationUser>()
.ToTable("dbo.AspNetUsers");
modelBuilder.Entity<IdentityRole>()
.ToTable("dbo.AspNetRoles");
modelBuilder.Entity<ApplicationRole>()
.ToTable("dbo.AspNetRoles");
modelBuilder.Entity<IdentityUserClaim>().ToTable("dbo.AspNetUserClaims");
modelBuilder.Entity<IdentityUserRole>().ToTable("dbo.AspNetUserRoles");
modelBuilder.Entity<IdentityUserRole>().HasKey((IdentityUserRole r) => new { UserId = r.UserId, RoleId = r.RoleId }).ToTable("dbo.AspNetUserRoles");
modelBuilder.Entity<IdentityUserLogin>().ToTable("dbo.AspNetUserLogins");
...
Then you should replace all ApplicationDbContext to SchoolContext entire your solution
You can pass the same connection string to both the dbContext then all tables of both the context will be created in same database.
You can implement authorization on your controllers using [Authorize] attribute.

Table name in data annotations in entity framework doesn't work.

I create a project in MVC 5 with entity framework 6. I am using code first approach. I want in one of the models define a different name for the table then the default. For that I use the System.ComponentModel.DataAnnotationsname space and define the class like this:
[Table(Name="Auditoria")]
public class AuditoriaDAL
{
[Key]
public int AuditoriaId { get; set; }
...
}
Running the project I get a database with a table with the name AuditoriaDALs. Why the table have this name a not the name that I define?
You are referencing the System.Data.Linq.Mapping.Table attribute when you need to reference System.ComponentModel.DataAnnotations.Schema.Table. So either do this:
[System.ComponentModel.DataAnnotations.Schema.Table("Auditoria")]
public class AuditoriaDAL
{
[Key]
public int AuditoriaId { get; set; }
...
}
Or better yet:
using System.ComponentModel.DataAnnotations.Schema;
...
[Table("Auditoria")]
public class AuditoriaDAL
{
[Key]
public int AuditoriaId { get; set; }
...
}
https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations(v=vs.110).aspx
you can set TableName like below :
public class MyContext : DBContext
{
public virtual DbSet<AuditoriaDAL> Auditorias { get; set; }
}
Or in OnModelCreating :
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<AuditoriaDAL>().ToTable("Auditorias");
}
The name= isn't necessary. You should try [Table("Auditoria")].

ASP.NET Identity 2.0 context adds "1" to table name.

I don't have any idea why it happens.
I have DbContext which inherits from IdentityDbContext:
public class TestContext : IdentityDbContext<ApplicationUser>
{
public TestContext()
: base("name=DomainModelContainer")
{
}
// protected override void OnModelCreating(DbModelBuilder modelBuilder)
// {
// throw new UnintentionalCodeFirstException();
// }
public virtual DbSet<AspNetRole> AspNetRoles { get; set; }
public virtual DbSet<AspNetUserClaim> AspNetUserClaims { get; set; }
public virtual DbSet<AspNetUserLogin> AspNetUserLogins { get; set; }
public virtual DbSet<AspNetUser> AspNetUsers { get; set; }
public virtual DbSet<Blog> Blogs { get; set; }
public virtual DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
modelBuilder.Entity<AspNetUserLogin>().HasKey<string>(l => l.UserId);
modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
base.OnModelCreating(modelBuilder);
//modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
So when I try to execute simple code. Something like
var testContext = new TestContext();
testContext.AspNetRoles.Count();
I get an exception Invalid object name 'dbo.AspNetRoles1'
Why EF decides to add "1" to table name? What is the point?

Entity Framework added s to my .dbo

I using "Entity Framework DbContext" at the moment I have got exception towars.dbo was not found. This is very strange because in my website I all the time ask about towar.dbo but no towars.dbo Do you know where is a problem?
- InnerException {"Invalid object name 'dbo.Towars'."} System.Exception {System.Data.SqlClient.SqlException}
My all things about Towar (of course different place in my program):
public class ProductController : Controller
{
//
// GET: /Product/
public ITowarRepository repository;
public ProductController(ITowarRepository productRepository)
{
repository = productRepository;
}
public ViewResult List()
{
return View(repository.Towar);
}
}
public interface ITowarRepository
{
IQueryable<Towar> Towar { get; }
}
public DbSet<Towar> Towar { get; set; }
public class EFTowarRepository : ITowarRepository
{
public EFDbContext context = new EFDbContext();
public IQueryable<Towar> Towar
{
get { return context.Towar; }
}
}
public class Towar
{
[Key]
public int Id_tow { get; set; }
public string Nazwa { get; set; }
public string Opis { get; set; }
public decimal Cena { get; set; }
public int Id_kat { get; set; }
}
Add the following line to your context:
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
You can tell EF to map to the table Towar by overriding the OnModelCreating method in your DBContext class with fluent API like this:
public class EFDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Towar>().ToTable("Towar");
}
}
Now EF will look for Towar table instead of Towars. If you do not have these tables created, there is some other problem you are having.
EF Code First automatically pluralizes the table names. Use a [Table] attribute to explicitly map the entity to a table name:
[Table("Towary")]
public class Towary
{
// Whatever properties
}
It looks like there's a way to disable pluralization gobally too, see Entity Framework Code First naming conventions - back to plural table names?.
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MVCDemo.Models
{
public class EmployeeContext : DbContext
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
For the sake of completeness #forty-two

Entity framework code first circular reference

I want an object to reference itself. How do I write this model? For eg.
public class Term
{
public int TermId { get; set; }
public string Name { get; set; }
public virtual Term PreviousTerm { get; set; }
public virtual int? PreviousTermId { get; set; }
}
The schema generated is:
TermId
Name
PreviousTermId
PreviousTerm_TermId
So apparently, PreviousTermId serves no purpose here as a relationship FK.
But when using automapper, I have to map to PreviousTermId, I cant create the new object PreviousTerm and assign the Id to that. How do I fix this?
Try specifying the mappings in onModel OnModelCreating event
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Term>().HasOptional(t =>t.PreviousTerm).WithMany().
HasForeignKey(t=>t.PreviousTermId);
}

Resources