Entity Framework Auto Migrations Primary Key - sql-server-2008

I have inherited a sql server database and an ASP.Net MVC 4 web application which is using Entity Framework 5.0 Code First with Auto Migrations . However, it appears the previous developer forgot to add a Primary Key to one of the tables. I am now trying to do this using Auto Migrations, however, it is not working, no errors either, just seems to be ignoring the command.
The table is like this
public int CourseDateHistoryID { get; set; }
public int CourseDateID { get; set; }
public int Event { get; set; }
//public string testProp{ get; set; }
And my mapping is like this to try and create the primary key on CourseDateHistoryID
this.HasKey(t => t.CourseDateHistoryID);
this.Property(t => t.CourseDateHistoryID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
I thought maybe the connection string was wrong or something, so I tried to add a dumby string property called testProp using auto migrations, but this worked fine.
Would anyone have any ideas as to why I cannot set CourseDateHistoryID as the PK using auto migrations?
Thanks for any help.

You can try manually updating the database using Update-Database -verbose command. It should show you the migration it's applying as well as the errors it encounters.
Or why not add another migration using the Add-Migration command and manually add primary key there, for example:
public partial class AddPrimaryKey : DbMigration
{
public override void Up()
{
AddPrimaryKey(table: "dto.table", column: "CourseDateHistoryID", name: "PK_CourseDateHistoryID");
}
public override void Down()
{
DropPrimaryKey(table: "dto.table", name: "PK_CourseDateHistoryID");
}
}
Hope this helps.

Related

.Net Core2 EF MySQL having issue while changing foreign key column to nullable

I am working on an application where I am using .Net Core 2, EF Core and MySQL as database server via Code First approach.
I have 2 tables:
User
Employee
User table is the main table which contains the user information and Employee table is the child table which has a column ID_User as shown below:
public class User : BaseEntity
{
public int ID_User { get; set; }
public string Name { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public virtual ICollection<Employee> Employees{get;set;}
}
public class Employee : Entity
{
public int ID_Employee { get; set; }
public string Name { get; set; }
public int ID_User { get; set; }
public virtual User User { get; set; }
}
Everything works perfectly when I use the above mapping and I have enough data in both the tables.
Now, I want to make the column ID_User in Employee table as nullable
To implement this change I made following change to my model:
public class Employee : Entity
{
public int ID_Employee { get; set; }
public string Name { get; set; }
public int? ID_User { get; set; }
public virtual User User { get; set; }
}
and in mapping file:
builder.HasOne(x=>x.User).WithMany(y=>y.Employees).HasForeignKey(z=>z.ID_User).IsRequired(false);
After running the dotnet ef migrations add empuser command it generated the following migration code:
migrationBuilder.DropForeignKey(
name: "FK_Employee_User_ID_User",
table: "Employee");
migrationBuilder.AlterColumn<int>(
name: "ID_User",
table: "Employee",
nullable: true,
oldClrType: typeof(int));
migrationBuilder.AddForeignKey(
name: "FK_Employee_User_ID_User",
table: "Employee",
column: "ID_User",
principalTable: "User",
principalColumn: "ID_User",
onDelete: ReferentialAction.Restrict);
Now when I run dotnet ef database update it is giving me the following error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'CONSTRAINT FK_Employee_User_ID_User' at line 1
Please help.
Thanks
Try putting the SQL statements directly into the MySQL Workbench.
Type "dotnet ef migrations script" in your commandprompt.
Copy the generated SQL script.
Paste it into your Workbench.
Check where the errors occur.
When I got similar errors using EF core 2 with MySQL this helped me understand the problem better and helped solve the problem. (for me it was a typing error). You can at least use this method to determine if it is an error in the migrations or in your SQL statements.
I know this is not a concrete solution, but I hope this will help you understand your problem and solve it :)
Have you checked foreign key name in database?
I have found bug from migration builder, where creating new table:
In my case I use EF Core 2.1 Mysql DotNet Connector bug
Where migration builder creates wrongly named foreign key name...
To avoid this wrongly named foreign key name:
fix for migration builder
If your foreign key is named wrongly, you can manually rename it in database and then your migration might work.
The key word CONSTRAINT is not supported for certain version of MYSQL . EF core generates drop constraint for dropping foreign key . I have to change the following:-
migrationBuilder.DropForeignKey(
name: "FK_XXXXX",
table: "XXXXXX");
to
migrationBuilder.Sql("ALTER TABLE XXXXXX DROP FOREIGN KEY FK_XXXXX");

Error when creating an MVC controller using composite key and EF 5

Using the Entity Framework tools I reverse engineered code first the POCO classes for a MySQL database into a class library. I created an MVC project that references this class library and I am trying to create a controller with read/write actions and views. After setting the model and data context classes and clicking "Add" I get this error:
EntityType xxx has no key defined. Define the key for this EntityType.
The problem is, in the map it is marked properly:
public UserApplicationMap()
{
// Primary Key
this.HasKey(t => new { t.UserID, t.AppID });
...
I tried doing this in the class:
public class UserApplication
{
[Key, Column(Order = 0)]
public int UserID { get; set; }
[Key, Column(Order = 1)]
public int AppID { get; set; }
But the compiler had a fit with the Column attribute and flagged it as invalid.
So I am a bit stumped. I really don't want to add an auto increment field to this table if I can just use a composite key.
I am using Visual Studio 2012, EF 5, MVC 4, and MySQL connector 6.6.4

SQL Server CE identifies a cyclical reference with Entity Framework Code First but SQL Server 2008 does not

I am working on an Entity Framework Code First project that has a fairly complex Data Model which deploys absolutely fine on SQL Server 2008.
However when creating an SQL Server CE database for some local End-To-End testing I get the following error message when EF creates the database:
System.Data.SqlServerCe.SqlCeException: The referential relationship will result in a cyclical reference that is not allowed. [ Constraint name = FK_Sites_Persons_PersonId ].
I have disabled the ManyToManyCascadeDeleteConvention in my DataContext model creation method, so that isn't the cause of the problem. The trouble I have is that the relationship in question looks fine in the SQL Server 2008 database- it appears to be a normal foreign key from what I can tell and I can't see anything flowing back in the other direction, although it is not impossible that there is a longer-path circular reference. I don't know why CE would fail and 2008 would succeed.
It turns out the problem was very simply solved- although I had disabled ManyToManyCascadeDeleteConvention I also needed to disable the OneToManyCascadeDeleteConvention to avoid the circular reference problem.
You might also consider explicitly defining the cascading updates and deletes rather than disabling them globally. Assume a model:
namespace Models
{
public class Parent
{
public Parent() { this.Children = new HashSet<Child>(); }
public int id { get; set; }
public string description { get; set; }
public ICollection<Child> Children { get; set; }
}
public class Child
{
public int id { get; set; }
public string description { get; set; }
public Parent Parent { get; set; }
}
}
Override the OnModelCreating in your context and use the fluent api to specify the cascade options for a given relationship.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Parent>().HasMany<Child>(p => p.Children).WithRequired(c => c.Parent).WillCascadeOnDelete(false);
base.OnModelCreating(modelBuilder);
}
Of course this is a simple example, but you can apply the same principle to your down-level entities and specifically exclude the cascaded delete that causes the circular reference.

When adding new Entity with existing referenced entity, EF 4.1 is tring to insert the existing referenced entity to the view

I encountered a strange situation.
I have a root entity (table) with refereance to another entity (view)
public class RootEntity
{
public int Id {get; set;}
public int SubEntityId {get; set;}
public SubEntity SubEntity {get; set;}
}
public class SubEntity
{
public int Id {get; set;}
}
When I set only the RootEntity.SubEntityId with existing SubEntityId All goes well.
But, when I set the Ref to as follow
RootEntity.SubEntity = attachedSubEntity
For whatever reason EF is trying to insert the attached SubEntity to the view and I get this
System.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column '****', table '****'; column does not allow nulls. INSERT fails.
I found the problem! SubEntity was fetched with AsNoTracking option.
I thought that using this option will solve the "Insert" problem but in fact he was the cause!
When I removed the AsNoTracking addition all goes well.
It's still weird because the problem occurred only when used UnitTesting (Nunit). But with WCF I not encountered the problem

Entity Type Has No Key Defined

Another 'Entity Type 'x' has no key defined' question, but I've set the [Key] attribute on a property so I'm a bit confused.
Here's my entity and context classes:
namespace DoctorDB.Models
{
public class Doctor
{
[Key]
public string GMCNumber;
[Required]
public string givenName;
[Required]
public string familyName;
public string MDUNumber;
public DateTime MDUExpiry;
public string MDUCover;
}
public class DoctorContext : DbContext
{
public DbSet<Doctor> Doctors { get; set; }
}
}
When I go to create my controller, I've selected to create it with the Entity Framework methods using this entity and context:
and I get this error:
My only thought is whether you can't successfully use [Key] on a string property. If you can't then fair enough, I'll work round it, but I'd be grateful if someone could confirm this one way or the other.
You need to change GMCNumber to a property not a field.
To help clarify, this line:
public string GMCNumber;
needs to become:
public string GMCNumber { get; set; }
I encountered the same error message when I had defined the property as private.
I ran into this post after facing a similar issue today. The problem was that I was attempting to create the scaffold after adding the [Key] attribute to my model and without compiling. Once I compiled with the [Key] attribute the scaffolding generated just fine.