Table name in data annotations in entity framework doesn't work. - asp.net-mvc

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")].

Related

ASP.NET MVC domain Models and Identity Models in same context - UserLogin has no key

I want my application models to be in the same DBContext that has the identity model. So I inserted my classes into the IdentityDbContext like this:
public partial class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("HumanTask")
{
}
public virtual DbSet<wfInstance> wfInstance { get; set; }
public virtual DbSet<wfService> wfService { get; set; }
public virtual DbSet<wfTask> wfTask { get; set; }
public virtual DbSet<wfWorkflow> wfWorkflow { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<wfTask>()
.Property(e => e.wfTaskId)
.IsUnicode(false);
modelBuilder.Entity<wfWorkflow>()
.Property(e => e.Name)
.IsUnicode(false);
}
}
}
now, when I try to create a new controller for one of my classes classes using the scaffold
I get a message like this:
I think I'm missing something on my OnModelCreating function, but I cant tell what. Help ?
From the error looks like you are missing key attributes for your IdentityUserLogin and IdentityUser role models. You will need to specify a key on your model like this:
public partial class IdentityUserLogin
{
[Key]
public string UserName { get; set; }
}
Or you can specify it with a fluent API
modelBuilder.Entity<IdentityUserLogin>()
.HasKey(t => t.UserName);

MVC migration is empty

I've added a simply Product-class (shown below) but when I run add-migration it generates an empty script. I guess this is hard to troubleshoot but any idea as to why this is?
public class Product
{
public int ProductID { get; set; }
[Required]
public string Name { get; set; }
[DataType(DataType.Currency)]
public decimal Price { get; set; }
}
public class ProductDBContext : DbContext
{
public DbSet<Product> Products { get; set; }
}
The migration file looks like this:
public partial class test : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
Have you added the according Class to your DB context?
public System.Data.Entity.DbSet YourDbSetName { get; set; }
Try Clearing out _MigrationHistory (and possible also opening your Project.Data.csproj to manually delete te migrations pending)
I found the answer here: solution

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);
}

Mapping EF 4.1 code-first models to database tables

I have been trying the model-first method when designing my application. We usually like to add a prefix to our tables in larger databases so it is easier to find stuff. For example:
sc_ = Shopping cart tables
wb_ = Water billing tables
ea_ = Employment Application tables
The class I have setup looks like this so far.
public class EFDbContext : DbContext
{
public DbSet<Transaction> Transactions { get; set; }
public DbSet<TransactionItem> TransactionItems { get; set; }
public DbSet<Response> Response { get; set; }
}
Web.config (set currently for local database testing):
<add name="EFDbContext" connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=database" providerName="System.Data.SqlClient"/>
What do I need to change so that the Transaction object gets linked to the sc_Transactions table? I haven't seen in my searching that clarifies this.
As a second question, do I have to manually create my tables?
You can override the OnModelCreating method from DbContext in your EFDbContext class:
public class EFDbContext : DbContext
{
public DbSet<Transaction> Transactions { get; set; }
public DbSet<TransactionItem> TransactionItems { get; set; }
public DbSet<Response> Response { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Transaction>().MapSingleType().ToTable("someTableNameHere");
}
}
See this post for more info.
You can use System.ComponentModel.DataAnnotations like so:
[Table("tblUser")]
public class User
{
public int ID { get; set; }
public string Name { get; set; }
}
Or with EF 4 you can override the OnModelCreating method to map your tables, which is quite powerful thing as you can map and adjust many things at once.
public class MyContext: DbContext
{
DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().MapSingleType().ToTable("tblUser");
}
}
For more info see:
EF4 CF custom database mapping
EF keynotes from the Build2011 event (custom mappings are at about
15 min or so)

Resources