I have the following Entity Framework Core 2.1 entity configuration:
public class CategoryConfiguration : IEntityTypeConfiguration<Category> {
public void Configure(EntityTypeBuilder<Category> builder) {
builder.With(x => {
x.ToTable("Categories");
x.Property(y => y.Id).UseSqlServerIdentityColumn();
x.Property(y => y.Name).IsRequired(true).HasMaxLength(40);
x.HasData(
new { Id = 1, Name = "A" },
new { Id = 2, Name = "B" },
new { Id = 3, Name = "C" },
new { Id = 4, Name = "D" }
);
});
}
}
When working on the project I would like to run migrations on Development environment.
So in this case I would like to add more than 4 categories ...
But before publishing the project to production I would like to run migrations on Production environment and add only the 4 categories of my example.
So I need to set a variable, when running migrations, that determines if live or test data is inserted into the database.
Is this possible? How can is this usually done?
in your Up method of migration, you can check for the Database name, and decide what to do based on your desired database. for example you can run a SqlQuery to insert the rows you want.
for getting database name you can use below code:
public override void Up()
{
var builder = new System.Data.SqlClient
.SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString);
var dbname = builder.DataSource;
if (dbname == "dbLive")
{
Sql("insert into table1 values('A' , 'B')");
}
}
I have a Users 1-* UserGroupLinks *-1 UserGroups Table structure and have created the following method:
public static string SaveUser(User user, List<UserGroup> newUserGroups)
{
using (var dbContext = new DCSEntities())
{
var existingUserGroups = user.UserGroups.ToList<UserGroup>();
existingUserGroups.ForEach(d => user.UserGroups.Remove(d));
newUserGroups.ForEach(a => user.UserGroups.Add(a));
dbContext.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
dbContext.SaveChanges();
return user.UserCode;
}
}
I would like to remove all the usergrouplinks for that user, and then add the new list of usergroups. When I run this method I get a violation of primary key on the UserGroups object/UsergroupLink table, indicating that my attempt at removing the existing usergrouplinks has failed. How can I resolve this error?
So I've changed the original code to confirm a suspicion.
public static string SaveUser(User user, List<UserGroup> newUserGroups)
{
using (var dbContext = new DCSEntities())
{
User dbUser = dbContext.Users.Where(u => u.UserCode == user.UserCode).Include(ug => ug.UserGroups).Include(s => s.Status).FirstOrDefault();
var existingUserGroups = dbUser.UserGroups.ToList<UserGroup>();
existingUserGroups.ForEach(d => dbUserUserGroups.Remove(d));
newUserGroups.ForEach(a => dbContext.UserGroups.Attach(a));
newUserGroups.ForEach(a => dbUser.UserGroups.Add(a));
dbContext.ObjectStateManager.ChangeObjectState(dbUser, EntityState.Modified);
dbContext.SaveChanges();
return dbUser.UserCode;
}
}
What I can confirm is that this code works when and only when adding new groups for that user. As soon as you try and add an existing group, it gives the primary key violation. It is almost as if the line
existingUserGroups.ForEach(d => dbUserUserGroups.Remove(d));
Is not taking effect.
My solution below is not elegant and therefore I have not marked it as an answer.
The idea to use 2 different dbcontexts actually worked, but as per my comment above, I don't think it is an elegant or the correct solution:
public static string SaveUser(User user, List<UserGroup> newUserGroups)
{
using (var dbContext = new DCSEntities())
{
User dbUser = dbContext.Users.Where(u => u.UserCode == user.UserCode).Include(ug => ug.UserGroups).Include(s => s.Status).FirstOrDefault();
var existingUserGroups = dbUser.UserGroups.ToList<UserGroup>();
existingUserGroups.ForEach(d => dbContext.UserGroups.Detach(d));
existingUserGroups.ForEach(d => dbUser.UserGroups.Remove(d));
dbContext.ObjectStateManager.ChangeObjectState(dbUser, EntityState.Modified);
dbContext.SaveChanges();
}
using (var dbContext = new DCSEntities())
{
User dbUser = dbContext.Users.Where(u => u.UserCode == user.UserCode).Include(ug => ug.UserGroups).Include(s => s.Status).FirstOrDefault();
newUserGroups.ForEach(a => dbContext.UserGroups.Attach(a));
newUserGroups.ForEach(a => dbUser.UserGroups.Add(a));
dbContext.ObjectStateManager.ChangeObjectState(dbUser, EntityState.Modified);
dbContext.SaveChanges();
return dbUser.UserCode;
}
}
I even went as far as to copy this solution verbatim and still got the primary key violation issue entity framework update many to many relationship: virtual or not
If anyone can explain why I need to do this with 2 different contexts I would greatly appreciate it. Thanx
Lets say we have the architecture model of web application where we have 1 database per 1 account. Database structure is the same for these accounts and differs only on data with in. How can i configurate a migrations in code first model.
Now I have next solution.
In the main method or in global.asax something like this:
var migration_config = new Configuration();
migration_config.TargetDatabase = new DbConnectionInfo("BlogContext");
var migrator = new DbMigrator(migration_config);
migrator.Update();
migration_config.TargetDatabase = new DbConnectionInfo("BlogContextCopy");
migrator = new DbMigrator(migration_config);
migrator.Update();
Connection strings for example in app_config file:
<connectionStrings>
<add name="BlogContext" providerName="System.Data.SqlClient" connectionString="Server=(localdb)\v11.0;Database=MigrationsDemo.BlogContext;Integrated Security=True;"/>
<add name="BlogContextCopy" providerName="System.Data.SqlClient" connectionString="Server=(localdb)\v11.0;Database=MigrationsDemo.BlogContextCopy;Integrated Security=True;"/>
</connectionStrings>
Configuration class and context:
internal sealed class Configuration : DbMigrationsConfiguration<MigrationsDemo.BlogContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(MigrationsDemo.BlogContext context) {
}
}
public class BlogContext : DbContext {
public BlogContext() {}
public BlogContext(string connection_name) : base(connection_name) {
}
public DbSet<Blog> Blogs { get; set; }
}
In addition to your excellent answer, you can use an external config file (i.e. "clients.json") instead of hardcoding them, put all the database infos in key-value pairs into the json file and load it during startup.
Then, by iterating over the key-value pairs, you can do the initialization.
The clients.json:
{
"DatabaseA": "DatabaseAConnectionString",
"DatabaseB": "DatabaseBConnectionString",
"DatabaseC": "DatabaseCConnectionString",
...
}
Provide a method to handle the migrations:
public static void MigrateDatabases(IDictionary<string,string> databaseConfigs)
{
foreach (var db in databaseConfigs)
{
var config = new Configuration
{
TargetDatabase = new DbConnectionInfo(db.Value, "System.Data.SqlClient")
};
var migrator = new DbMigrator(config);
migrator.Update();
}
}
Then during startup, (I use OWIN, so it's in my Startup.cs, could also be global.asax.cs):
string json;
var path = HttpRuntime.AppDomainAppPath;
using (var reader = new StreamReader(path + #"Config\clients.json"))
{
json = reader.ReadToEnd();
}
var databases = JsonConvert.DeserializeObject<IDictionary<string, string>>(json);
MigrateDatabases(databases);
Works like a charm for me :)
See the page on automatic migrations during application startup.
If you use this method to apply your migrations, you can use any connection string (or whatever method you have to identify exactly which database to connect to) and upon connection, the migration will be performed.
I have a project that I created and enabled Migrations on. It created it with 4.3 so I think it is the latest. I have some code in the constructor of the context that executes the update (see code below) and that seems to work everytime I add something like a nullable string column or do something that does not change the database in non consistent manner. My scenario is I change my model, and when I watch sql trace, it does the alter columns for me automatically.
My question is I want to do the "up" and "down" methods but am confused on when they run. That is say I'm on version 1 now, I put some code in my "up" method to add a column, then later when I want to go to version 3, how does it know which "up" method to call?
Confused. -Peter
namespace MigrationsAutomaticDemo.Migrations
{
using System.Data.Entity.Migrations;
public partial class AddBlogRating : DbMigration
{
public override void Up()
{
AddColumn("Blogs", "Rating", c => c.Int(nullable: false, defaultValue: 3));
}
public override void Down()
{
DropColumn("Blogs", "Rating");
}
}
}
,
public SiteDB()
{
UpdateDatabase();
}
// http://joshmouch.wordpress.com/2012/04/22/entity-framework-code-first-migrations-executing-migrations-using-code-not-powershell-commands/
public static int IsMigrating = 0;
private static void UpdateDatabase()
{
if (0 == Interlocked.Exchange(ref IsMigrating, 1))
{
// Manually creating configuration:
var migratorConfig = new DbMigrationsConfiguration<SiteDB>();
migratorConfig.AutomaticMigrationsEnabled = true;
// Using configuration defined in project:
//var migratorConfig = new DbMigrationsConfiguration();
// 3
//var dbMigrator = new DbMigrator(new Settings());
var dbMigrator = new DbMigrator(migratorConfig);
dbMigrator.Update();
Interlocked.Exchange(ref IsMigrating, 0);
}
}
If you enable the automatic migration in the migration configuration, then you don't need to specify the target migration. The migrator will automatically scaffold the changes based on the snapshot of current context and target database.
var migratorConfig = new DbMigrationsConfiguration<SiteDB>();
migratorConfig.AutomaticMigrationsEnabled = true;
In your case, you want to upgrade your database by using specific migration. All you need to do is mentioning explicitly which migration to upgrade.
Configuration configuration = new Configuration();
DbMigrator migrator = new DbMigrator(configuration);
migrator.Update("201204250656061_AddBlogRatingVersion2");
migrator.Update("201204250656061_AddBlogRatingVersion3");
migrator.Update("201204250656061_AddBlogRatingVersionX");
I use entity framework migration (in Automatic migration mode). Everything is okay, but I have one question:
How should I seed data when I have many-to-many relationships?
For example, I have two model classes:
public class Parcel
{
public int Id { get; set; }
public string Description { get; set; }
public double Weight { get; set; }
public virtual ICollection<BuyingItem> Items { get; set; }
}
public class BuyingItem
{
public int Id { get; set; }
public decimal Price { get; set; }
public virtual ICollection<Parcel> Parcels { get; set; }
}
I understand how to seed simple data (for PaymentSystem class) and one-to-many relationships, but what code should I write in the Seed method to generate some instances of Parcel and BuyingItem? I mean using DbContext.AddOrUpdate(), because I don't want to duplicate data every time I run Update-Database.
protected override void Seed(ParcelDbContext context)
{
context.AddOrUpdate(ps => ps.Id,
new PaymentSystem { Id = 1, Name = "Visa" },
new PaymentSystem { Id = 2, Name = "PayPal" },
new PaymentSystem { Id = 3, Name = "Cash" });
}
protected override void Seed(Context context)
{
base.Seed(context);
// This will create Parcel, BuyingItems and relations only once
context.AddOrUpdate(new Parcel()
{
Id = 1,
Description = "Test",
Items = new List<BuyingItem>
{
new BuyingItem() { Id = 1, Price = 10M },
new BuyingItem() { Id = 2, Price = 20M }
}
});
context.SaveChanges();
}
This code creates Parcel, BuyingItems and their relationship, but if I need the same BuyingItem in another Parcel (they have a many-to-many relationship) and I repeat this code for the second parcel - it will duplicate BuyingItems in the database (though I set the same Ids).
Example:
protected override void Seed(Context context)
{
base.Seed(context);
context.AddOrUpdate(new Parcel()
{
Id = 1,
Description = "Test",
Items = new List<BuyingItem>
{
new BuyingItem() { Id = 1, Price = 10M },
new BuyingItem() { Id = 2, Price = 20M }
}
});
context.AddOrUpdate(new Parcel()
{
Id = 2,
Description = "Test2",
Items = new List<BuyingItem>
{
new BuyingItem() { Id = 1, Price = 10M },
new BuyingItem() { Id = 2, Price = 20M }
}
});
context.SaveChanges();
}
How can I add the same BuyingItem in different Parcels?
Updated Answer
Make sure you read "Using AddOrUpdate Properly" section below for a complete answer.
First of all, let's create a composite primary key (consisting of parcel id and item id) to eliminate duplicates. Add the following method in the DbContext class:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Parcel>()
.HasMany(p => p.Items)
.WithMany(r => r.Parcels)
.Map(m =>
{
m.ToTable("ParcelItems");
m.MapLeftKey("ParcelId");
m.MapRightKey("BuyingItemId");
});
}
Then implement the Seed method like so:
protected override void Seed(Context context)
{
context.Parcels.AddOrUpdate(p => p.Id,
new Parcel { Id = 1, Description = "Parcel 1", Weight = 1.0 },
new Parcel { Id = 2, Description = "Parcel 2", Weight = 2.0 },
new Parcel { Id = 3, Description = "Parcel 3", Weight = 3.0 });
context.BuyingItems.AddOrUpdate(b => b.Id,
new BuyingItem { Id = 1, Price = 10m },
new BuyingItem { Id = 2, Price = 20m });
// Make sure that the above entities are created in the database
context.SaveChanges();
var p1 = context.Parcels.Find(1);
// Uncomment the following line if you are not using lazy loading.
//context.Entry(p1).Collection(p => p.Items).Load();
var p2 = context.Parcels.Find(2);
// Uncomment the following line if you are not using lazy loading.
//context.Entry(p2).Collection(p => p.Items).Load();
var i1 = context.BuyingItems.Find(1);
var i2 = context.BuyingItems.Find(2);
p1.Items.Add(i1);
p1.Items.Add(i2);
// Uncomment to test whether this fails or not, it will work, and guess what, no duplicates!!!
//p1.Items.Add(i1);
//p1.Items.Add(i1);
//p1.Items.Add(i1);
//p1.Items.Add(i1);
//p1.Items.Add(i1);
p2.Items.Add(i1);
p2.Items.Add(i2);
// The following WON'T work, since we're assigning a new collection, it'll try to insert duplicate values only to fail.
//p1.Items = new[] { i1, i2 };
//p2.Items = new[] { i2 };
}
Here we make sure that the entities are created/updated in the database by calling context.SaveChanges() within the Seed method. After that, we retrieve the required parcel and buying item objects using context. Thereafter we use the Items property (which is a collection) on the Parcel objects to add BuyingItem as we please.
Please note, no matter how many times we call the Add method using the same item object, we don't end up with primary key violation. That is because EF internally uses HashSet<T> to manage the Parcel.Items collection. A HashSet<Item>, by its nature, won't let you add duplicate items.
Moreover, if you somehow manage to circumvent this EF behavior as I have demonstrated in the example, our primary key won't let the duplicates in.
Using AddOrUpdate Properly
When you use a typical Id field (int, identity) as an identifier expression with AddOrUpdate method, you should exercise caution.
In this instance, if you manually delete one of the rows from the Parcel table, you'll end up creating duplicates every time you run the Seed method (even with the updated Seed method I have provided above).
Consider the following code,
context.Parcels.AddOrUpdate(p => p.Id,
new Parcel { Id = 1, Description = "Parcel 1", Weight = 1.0 },
new Parcel { Id = 2, Description = "Parcel 1", Weight = 1.0 },
new Parcel { Id = 3, Description = "Parcel 1", Weight = 1.0 }
);
Technically (considering the surrogate Id here), the rows are unique, but from the end-user point of view, they are duplicates.
The true solution here is to use the Description field as an identifier expression. Add this attribute to the Description property of the Parcel class to make it unique: [MaxLength(255), Index(IsUnique=true)]. Update the following snippets in the Seed method:
context.Parcels.AddOrUpdate(p => p.Description,
new Parcel { Description = "Parcel 1", Weight = 1.0 },
new Parcel { Description = "Parcel 2", Weight = 2.0 },
new Parcel { Description = "Parcel 3", Weight = 3.0 });
// Make sure that the above entities are created in the database
context.SaveChanges();
var p1 = context.Parcels.Single(p => p.Description == "Parcel 1");
Note, I'm not using the Id field as EF is going to ignore it while inserting rows. And we are using Description to retrieve the correct parcel object, no matter what Id value is.
Old Answer
I would like to add a few observations here:
Using Id is probably not going to do any good if the Id column is a database generated field. EF is going to ignore it.
This method seems to be working fine when the Seed method is run once. It won't create any duplicates, however, if you run it for a second time (and most of us have to do that often), it may inject duplicates. In my case it did.
This tutorial by Tom Dykstra showed me the right way of doing it. It works because we don't take anything for granted. We don't specify IDs. Instead, we query the context by known unique keys and add related entities (which again are acquired by querying context) to them. It worked like a charm in my case.
You must fill many-to-many relation in the same way as you build many-to-many relation in any EF code:
protected override void Seed(Context context)
{
base.Seed(context);
// This will create Parcel, BuyingItems and relations only once
context.AddOrUpdate(new Parcel()
{
Id = 1,
Description = "Test",
Items = new List<BuyingItem>
{
new BuyingItem() { Id = 1, Price = 10M },
new BuyingItem() { Id = 2, Price = 20M }
}
});
context.SaveChanges();
}
Specifying Id which will be used in database is crucial otherwise each Update-Database will create new records.
AddOrUpdate doesn't support changing relations in any way so you cannot use it to add or remove relations in next migration. If you need it you must manually remove relation by loading Parcel with BuyingItems and calling Remove or Add on navigation collection to break or add new relation.
Ok. I understand how I should be in that situation:
protected override void Seed(Context context)
{
base.Seed(context);
var buyingItems = new[]
{
new BuyingItem
{
Id = 1,
Price = 10m
},
new BuyingItem
{
Id = 2,
Price = 20m,
}
}
context.AddOrUpdate(new Parcel()
{
Id = 1,
Description = "Test",
Items = new List<BuyingItem>
{
buyingItems[0],
buyingItems[1]
}
},
new Parcel()
{
Id = 2,
Description = "Test2",
Items = new List<BuyingItem>
{
buyingItems[0],
buyingItems[1]
}
});
context.SaveChanges();
}
There are no duplicates in database.
Thank you, Ladislav, you gave me a right vector to find a solution for my task.