Entity Framework and migration issue - entity-framework

this is my sample class
public class Contacts
{
[Key]
public int ContactID { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public bool IsDefault { get; set; }
public int AddressID { get; set; }
public virtual Addresses Customer { get; set; }
}
in our database EF already create table for Contacts. i add one new field to contact class and that is public bool IsDefault { get; set; }
when i try to migrate like this way
Enable-Migrations
Add-Migration AddIsDefault
Update-Database -Verbose
then VS show new fields is added. the sql i got for that from package manager console like
ALTER TABLE [dbo].[Contacts] ADD [IsDefault] [bit] NOT NULL DEFAULT 0
ALTER TABLE [dbo].[Customers] ADD [Address1] [nvarchar](max)
ALTER TABLE [dbo].[Customers] ADD [Address2] [nvarchar](max)
ALTER TABLE [dbo].[Customers] ADD [Phone] [nvarchar](max)
ALTER TABLE [dbo].[Customers] ADD [Fax] [nvarchar](max)
INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])
VALUES (N'201609071306198_AddIsDefault', N'EFTest.TestDBContext',
i though new fields has been added but when i query contacts table then saw no new field has been added.
migration details
namespace EFTest.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AddIsDefault : DbMigration
{
public override void Up()
{
AddColumn("dbo.Contacts", "IsDefault", c => c.Boolean(nullable: false));
AddColumn("dbo.Customers", "Address1", c => c.String());
AddColumn("dbo.Customers", "Address2", c => c.String());
AddColumn("dbo.Customers", "Phone", c => c.String());
AddColumn("dbo.Customers", "Fax", c => c.String());
}
public override void Down()
{
DropColumn("dbo.Customers", "Fax");
DropColumn("dbo.Customers", "Phone");
DropColumn("dbo.Customers", "Address2");
DropColumn("dbo.Customers", "Address1");
DropColumn("dbo.Contacts", "IsDefault");
}
}
}
i did not write any code for seed. is it the reason for which new field has not been added to my contacts table ?
please guide me why new field called IsDefault not being added to table event after migration command issuing ? thanks
my updated post
public class TestDBContext : DbContext
{
public TestDBContext()
: base("name=TestDBContext")
{
}
public DbSet<Customer> Customer { get; set; }
public DbSet<Addresses> Addresses { get; set; }
public DbSet<Contacts> Contacts { get; set; }
}
connection string is in app.config file
<connectionStrings>
<add name="TestDBContext" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\DB\TestDB.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Issue solved
problem was at my end.
my connection string was looking like
EF migration do not understand the meaning of DataDirectory path
the moment i hard code the db file path like below connection then issue was solved.
<connectionStrings>
<add name="TestDBContext" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=c:\users\user1\documents\visual studio 2013\Projects\EFTest\EFTest\DB\TestDB.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>

Related

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.

Why it is trying to insert NULL in primary key property id.. MVC5 EF6

I am using Entity Framework 6 Code First MVC5.Here is my class:
Offer.cs
public class Offer
{
public int Id { get; set; }
[Required]
public string ListOffer { get; set; }
}
Here is my controller
[HttpPost]
public ActionResult Create(OfferFormViewModel viewModel)
{
var offer = new Offer
{
ListOffer = viewModel.ListOffer,
};
_context.Offers.Add(offer);
_context.SaveChanges();
return RedirectToAction("MyOffers", "Offers");
}
OfferFormViewModel.cs
public class OfferFormViewModel {
public int Id { get; set; }
[Required]
public string ListOffer { get; set; }
}
When I try to insert a record in offers table, it works fine on my machine and inserts record in the database and it automatically assigns value to id column. But when I deploy the application it throws the exception
System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'Id', table 'DefaultConnection.dbo.Offers'; column does
not allow nulls. INSERT fails. The statement has been terminated.
My question is why is it trying to insert NULL in Id column when I deploy the application and not when I run the code without deployment?
When I deployed the application I copied the database to the server. On the server the Id column was not set to primary key and it was not an identity column either. I think something went wrong while copying the database to the server. That's why it was throwing the exception.
Use this Model and also update database with migration u can do this by following steps:
Open Tools > NuGet Package Manager > Package Manager Console.
enterenable-migrations in the Package Manager Console
enteradd-migration {name}(make sure your application can built without any error).
enterupdate-database.
public class Offer
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public string ListOffer { get; set; }
}
You should use auto-increment, using Data Annotation:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
or FluentAPI
modelBuilder.Entity<Offers>()
.Property(c => c.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

Convert EF Model Property to Navigation Property

What are the step to convert/migrate a model property into a navigation property (create a new class and create a foreign key relationship, using EF Code First Migration.
In the example below, I want to convert the Student class property Country into a navigational property, without losing in data.
Current Model
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
Proposed Model
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public int CountryID { get; set; }
public virtual Country Country { get; set; }
}
public class Country
{
public int ID { get; set; }
public string Country { get; set; }
}
Add-Migration NavigationProperty
public override void Up()
{
CreateTable(
"dbo.Countries",
c => new
{
ID = c.Int(nullable: false, identity: true),
CountryName = c.String(),
})
.PrimaryKey(t => t.ID);
AddColumn("dbo.Students", "CountryID", c => c.Int(nullable: false));
CreateIndex("dbo.Students", "CountryID");
AddForeignKey("dbo.Students", "CountryID", "dbo.Countries", "ID", cascadeDelete: true);
DropColumn("dbo.Students", "Country");
}
Update-Database Error
System.Data.SqlClient.SqlException (0x80131904): The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Students_dbo.Countries_CountryID". The conflict occurred in database "aspnet-navprop-20141009041805", table "dbo.Countries", column 'ID'.

Develop Entity Framework class that will define a .mdf database

I am trying to develop Entity Framework class that will define a .mdf database already created and filled leading up to actually creating one and filling it.
Error:
One or more validation errors were detected during model generation:
testclass.test: : EntityType 'test' has no key defined. Define the key for this EntityType.
testData: EntityType: EntitySet 'testData' is based on type 'test' that has no keys defined.
Code:
using System.Data.Entity;
namespace testclass
{
public class test
{
public int idt { get; set; }
public string datetime { get; set; }
public string col1 { get; set; }
public string col2 { get; set; }
public string col3 { get; set; }
}
public class TestDbContext : DbContext
{
public DbSet<test> testData { get; set; }
}
public class testRepository
{
public List<test> Gettest()
{
TestDbContext testDbContext = new TestDbContext();
return testDbContext.testData.ToList();
}
}
}
connection string:
<connectionStrings>
<add name="TestDbContext" connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=C:\folders\testclass\testclass\App_Data\Data.mdf;User Instance=true;" providerName="System.Data.SqlClient" />
</connectionStrings>
There is some issues with your code:
the main is the lack of a primary key on your entity: EF can infer some keys if their names match some conventions : "Id", "ID", "testId"... So either use one of these standard names or explicitly mark your property as a primary key with the [Key] attribute:
[Key]
public int idt { get; set; }
to ensure proper cleanup of the resources allocated by the DbContext you should wrap its usage in a using block:
using (TestDbContext testDbContext = new TestDbContext())
{
return testDbContext.testData.ToList();
}
in .Net the naming conventions are: CamelCase for everything except local variables and fields; so testclass should be Testclass, col1 should be Col1, testData should be TestData...

Schema not being created when using Entity Framework 4.1 and Code First?

I am running tests against my context and thought EF 4.1 was supposed to create the schema for me in my database, it is not though. I am getting an error that db.Users does not exist in my database, but it is because it is not being created.
public class MyContext: DbContext
{
DbSet<Address> Addresses { get; set; }
DbSet<Region> Regions { get; set; }
DbSet<Country> Countries { get; set; }
DbSet<Contact> Contacts { get; set; }
DbSet<User> Users { get; set; }
}
Here is my db connection string:
<add name="MyContext" connectionString="Data Source=DIW-7-1;Initial Catalog=TestDb;Integrated Security=True" providerName="System.Data.SqlClient" />
I already had a database created without tables so the default initializer was not dropping my database to create the tables. Thanks to Ladislav Mrnka for the help, again!