EF Code-First cached bad table name? - entity-framework

I have a console application that is using code first Entity Framework 4.3.1. I created a class, a DbContext, a DbSet, and I have a database connection.
The issue is that I mispelled the table name and the program threw an error. I changed the name in the DbSet and the system keeps throwing the same error that has the old name.
Example:
public DbSet<SHIPPER> SHIPPERs { get; set; }
This could not find the SHIPPERs table in SQL server. No problem. I changed it to
public DbSet<SHIPPER> SHIPPER { get; set; }
and I get Invalid object name 'dbo.SHIPPERs'."
I did a search in Visual Studio for SHIPPERs and nothing was returned. What am I missing?
Note: I created another DbSet for a different table and that works.

The problem was with pluralization. Add the following code inside of your DbContext class to fix the issue:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

Related

Entity Framework code-first migrations using SQL views

I have decided to use code first migrations. I did not use them before. I have, in the past just created the models and then added the tables as needed to the database. I use several SQL Views in my project. I create the SQL View and then create a model for it. It works fine, however when I do migrations it treats them like tables and adds them to the database as a table.
I could use the
modelBuilder.Ignore<AspNetUsers>();
for the view, but is there any way to actually create the SQL view from the model? Below is one of my SQLView entities
[NotMapped]
public IDbSet<StockReportView> StockReportView { get; set; }
If not then I will just continue to create the SQL views and create the model and then add it to the OnModelCreating as modelBuilder.Ignore<StockReportView>();
Thanks for all your help.
UPDATE:
I found a question that was closed but had some answers. I Implemented what they said. Which was:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace SomeProject.Data
{
[Table("SomeView")]
public class SomeView
{
[Key]
public int NameID { get; set; }
public string Name { get; set; }
}
}
This deleted all of the tables it created That were SQL Views, But did not create the SQLViews.

Azure Mobile Apps - POST to table with foreign key "Bad Request" 400 error

I'm hoping this is a simple question. I've created an Azure Mobile Apps project based upon the sample ToDo project, adding my own tables/data objects. The problem I'm having is adding/POSTing records to a table that has a foreign key relationship to another. The following is my Employee table data object:
public class Employee : EntityData
{
public string Name { get; set; }
public string EmailAddress { get; set; }
public bool IsActive { get; set; }
public string EmployeeTypeId { get; set; }
public virtual EmployeeType EmployeeType { get; set; }
}
...and this is my EmployeeType data object:
public class EmployeeType : EntityData
{
public string EmpType { get; set; }
public bool IsActive { get; set; }
}
The virtual EmployeeType property in the Employee class was necessary, I believe, to create the relationship with the EmployeeType table when using EF Code First to create the tables in the database. (At least, that's what I understand, and it worked) I am able to insert records from my Xamarin client app into the EmployeeType table using the InsertAsync method, but I receive a "Bad Request" 400 error when trying to insert into the Employee table.
I've looked around quite a bit for solutions, but everything refers to Azure Mobile Services and not Apps. If need be, I can update this question with my client side model classes (I'm on my PC now and don't have access to the Xamarin Studio project on my Mac). For reference, these classes are pretty much the same as the data objects - just each property is decorated with the JsonProperty attribute, except the virtual property outlined in the service. And for completeness, I did try adding that property to the client object and it still threw the "Bad Request" 400 error.
Thanks for any direction you can offer me.
Most likely, the problem is happening when trying to map the foreign key. Are you specifying all of the fields for employee type? I recommend that you do the following:
Use Fiddler or attach a delegating handler to your client to see what the outgoing request looks like. Update your comment with the JSON body. See https://github.com/Azure/azure-mobile-apps/wiki/Help,-my-app-isn't-working!#log-outgoing-requests-in-managed-client-xamarin-windows.
Attach a debugger to your server project. You can do this while running locally or after your solution is deployed to Azure, but you'll have better performance if you run locally. See https://github.com/Azure/azure-mobile-apps/wiki/Help,-my-app-isn't-working!#remote-debugging-net-server-sdk.
I suspect that the problem is that EmployeeType ends up being null in your deserialized object, and then Entity Framework rejects the DB insert.
Could you get more information from the bad request? Try adding this to the table controller
protected override void Initialize(HttpControllerContext controllerContext)
{
controllerContext.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
}

Using EntityFramework.HierarchyId in CodeFirst approach, The Type hierarchyid is not qualified with a namespace or alias

I'm starting new project and I'd like to use HierarchyID in my DB model and CodeFirst approach. So I added EntityFramework.HierarchyId using nuget.
But when I run Update-Database, I receive this exception:
Schema specified is not valid. Errors:
(0,0) : error 0040: The Type hierarchyid is not qualified with a namespace or alias. Only primitive types can be used without qualification.
This is how my table looks like:
public class Activity
{
[Key]
public int ActivityId { get; set; }
public HierarchyId ActivityPath { get; set; }
public string Name { get; set; }
}
I know that I had to miss samething easy, but I'm not able to find useful sample on Google. Thank you!
I finally found a reason of this issue.
Because the whole solution is new, it was using ./express database (I don't know why it chose exactly this instance... maybe it's default). And even if I have installed MS SQL 2012, instance of ./express is SQL2005 -> no hierarchyId support. When I specified connection string explicitly to newer version, problem solved.
I'll keep this post to help others... Don't forget to vote up if you are one of them.

ef6 database migrations change table name

I am using EF6 code first and database migrations to keep my new database up do date.
I wanted to change the name of one of the database tables from "contacts" to "contact".
So in EF I change the name of the class and in the customised DBContext class I rename Contacts to Contact so it is now showing;
public DbSet<Contact> Contact { get; set; }
However I run the database migrations with Update-Database -Verbose -Force and no change is made.
To find out what is going on I put a new field in, and it tries to update the Contacts table rather than Contact which it needs to create.
So how do I fix this?
Try removing Pluralizing:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
I found the answer which is to use the following attribute in from of the class declaration;
[Table("Contact")]

How EF knew what table in SQL Server the DBContext class should bind to

I'm currently starting ASP.NET MVC 4 and in the book I am reading, EF was used. We were doing a sample project and we created a Products table in localdb. After creating the table, we created a DbContext-derived class. Here is the class:
public class EFDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
}
and a repository that uses this:
public class EFProductRepository : IProductRepository
{
private EFDbContext context = new EFDbContext();
public IQueryable<Product> Products
{
get { return context.Products; }
}
}
Now on the MVC project, we added this line in the connectionstring
<add name="EFDbContext" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=SportsStore;Integrated Security=True" providerName="System.Data.SqlClient" />
And when project was run, content of Products table was loaded in browser. My questions are:
How did EF knew what database to use? I'm guessing the EFDbContext name in connection string corresponds to the EFDbContext class as changing the name produces no output. But how were they "connected" to each other? EF automatically does this based on name?
How did EF knew what table to get data from? Initially, I thought it was based on name of table (Products) which should be the same as property name, but I tried renaming property to some other name (I tried naming it XXX) but still the data was displayed.
You already answered your first question, EF uses convention over configuration. EF uses the connection string name that matches with the class name of your DbContext class.
To answer #2, EF uses "Product" as shown below to name the table, and this is how it knows what table to get the date from as well. The name you use in your code can be anything like "SomeRandonName" and that does not change anything as that is mapped to the table named Product.
public DbSet<Product> SomeRandomName { get; set; }