I have two apps in one solution: ConsoleApp and MVC web app. Database was created by MVC web app, so after creating Console App I have added a reference to Web app.
Now I try to create an object and save it to database from ConsoleApp but I get "cannot attach database" error.
Web.config and App.config have the same cs:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-xxx-20180721085700.mdf;Initial Catalog=aspnet-xxx-20180721085700;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
When I comment out App.config connection string, code works fine, but creates another database "DefaultConnection" instead of working on "xxx" database.
My Console App has simple void:
public void NewAnimal()
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
db.Database.Connection.Open();
//'Cannot attach the file 'C: \Users\... 20180721085700.mdf' as database 'aspnet ... 20180721085700'.'
Animal animal = new Animal();
animal.Name = "Dog";
animal.Description = "Has 4 legs and tail";
db.Animals.Add(animal);
db.SaveChanges();
}
}
I use WebApp database context:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public DbSet<Animal> Animals{ get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
How to use the same database in two apps in one solution?