Entity Framework Migrations Command and Program.cs - entity-framework

When I run "dotnet ef migrations" commands, my program.cs is not being run. I am setting the project that contains the program.cs, as my startup project. But when I run the ef migrations commands, it's calling the empty constructor for my applicationDbContext. It's not calling the empty constructor for my ApplicationDbContext, instead of the one with parameters.
Why is it calling the wrong constructor?
I am using Entity Framework for a web application. I am trying to create a new migration, but I am getting the following error:
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type ApplicationDbContext. System.InvalidOperationException: Unable to resolve service for type Microsoft.EntityFrameworkCore.DbContextOptions
Here is my ApplicationDbContext
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public ApplicationDbContext()
: base()
{
}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Stock> Stocks { get; set; } = default!;
public DbSet<Portfolio> Portfolios { get; set; } = default!;
public DbSet<StockHolding> StockHoldings { get; set; } = default!;
public DbSet<Order> Orders { get; set; } = default!;
public DbSet<Transaction> Transactions { get; set; } = default!;
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Stock>().Property(p => p.Id).ValueGeneratedOnAdd();
base.OnModelCreating(builder);
}
}
I have been trying all kinds of solutions and research. I am expecting the "dotnet ef migrations" commands to call the constructor from program.cs, which passes the sqlconnectionstring. Instead, it is calling the empty constructor from I don't know where....

Related

Entity Framework Core 2.2 Owned Entity with UseLazyLoadingProxies

I am currently working on a codebase, to which I want to add a number of new entities with corresponding owned entities. Because, in some other part of the codebase I won't touch, UseLazyLoadingProxies is called; I receive the following exception:
System.InvalidOperationException : Navigation property 'Foo' on entity type 'FooOwner' is not virtual. UseLazyLoadingProxies requires all entity types to be public, unsealed, have virtual navigation properties, and have a public or protected constructor.
If I mark the property as virtual, the owned entity goes into a new table; which I do not want either.
According to github issues I encountered, these seem to be the expected behavior.
My question is this: Is there a way to work around this problem, such that, I can somehow mark the owned entity to be stored in the same table as the owner entity, and if possible to be always Included, eagerly loaded.
using System.Diagnostics;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using NUnit.Framework;
namespace StackOverflowObjectContext.Tests
{
public class Foo
{
public long Id { get; set; }
public int Data { get; set; }
}
public class FooOwner
{
public int Id { get; set; }
public Foo Foo { get; set; }
}
public class FooOwnerMap : IEntityTypeConfiguration<FooOwner>
{
public void Configure(EntityTypeBuilder<FooOwner> builder)
{
builder.HasKey(x => x.Id);
builder.HasOne(x => x.Foo);
}
}
public class StackOverflowObjectContext : DbContext
{
public StackOverflowObjectContext(DbContextOptions options) : base(options) { }
DbSet<FooOwner> FooOwners { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new FooOwnerMap());
base.OnModelCreating(modelBuilder);
}
}
[TestFixture]
public class StackOverflowTest
{
StackOverflowObjectContext _objectContext;
[SetUp]
public void SetUp()
{
var builder = new DbContextOptionsBuilder<StackOverflowObjectContext>()
.UseSqlServer(#"Data Source=.\SQLEXPRESS;Initial Catalog=StackOverflow;Integrated Security=True")
.UseLazyLoadingProxies();
_objectContext = new StackOverflowObjectContext(builder.Options);
}
[Test]
public void CanGenerateCreateScript()
{
var script = _objectContext.Database.GenerateCreateScript();
Debug.WriteLine(script);
}
}
}
You should use OwnsOne instead of HasOne

Table Does Not Exist while using EF CodeFirst 6 and Oracle.ManagedDataAccess

I am creating a MVC application using EF 6.0.0.0 and ODP.Net Oracle.ManagedDataAccess version 4.121.2.0 for the data access.
And when I load the Locations/Create.cshtml page I got the following Exception:
ORA-00942: table or view does not exist
While I have used the link below
Table Does Not Exist while using EF 6 and Oracle.ManagedDataAccess
Here is how my Context :
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext()
: base("QAContextConnectionString")
{
Database.SetInitializer<ApplicationDbContext>(null);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("AMICOS");
base.OnModelCreating(modelBuilder);
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
public DbSet<Location> Locations { get; set; }
}

Unity.MVC register autogenerated dbcontext from ef

I have an autogenerated dbcontext from EF. I've created a partial class of this autogenerated EF class so I can make it implement an interface so that I can pass that interface to my service that will use it. That'll get passed in via Unity.MVC DI framework. When I try to register this interface to the actual class I'm getting an error:
"There is no implicit reference conversion from ContactsEntities to IContactsEntities."
I'm not sure why I'm getting that or how to solve it.
EF Autogen file:
public partial class ContactsEntities : DbContext
{
public ContactsEntities()
: base("name=ContactsEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Contact> Contacts { get; set; }
}
My file:
public interface IContactsEntities
{
DbSet<Contact> Contacts { get; set; }
}
public partial class ContactsEntities : IContactsEntities
{
public virtual DbSet<Contact> Contacts { get; set; }
}
Unity registering that gives the error:
container.RegisterType<IContactsEntities, ContactsEntities>();

How can I use Entity Framework from ASP.NET MVC 4?

I am getting started with ASP.NET and I have a problem. I created an MVC4 application in the Visual Studio. Then to the Models I added an ADO.NET Entity Data Model with the Database first method. Everything okay until I try to add a new Controller when I get an error message: 'Projectname.Models.Tablename' is not part of specified 'Projectname.Models.Contextname' class and the 'Projectname.Models.Contextname' class could not be modified to add a DbSet<Projectname.Models.Tablename> property to it.
What is my mistake?
Here is my generated model:
public partial class Example
{
public int ID { get; set; }
public string Name { get; set; }
}
End here is my generated context:
public partial class TestEntities : DbContext
{
public TestEntities()
: base("name=TestEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Example> Example { get; set; }
}

Why is EF code first throwing model backing context exception? Using 4.0.3

Heres the exception:
The model backing the 'ScannerContext' context has changed since the
database was created. Consider using Code First Migrations to update
the database (http://go.microsoft.com/fwlink/?LinkId=238269).
I get this everytime I run my application. I cant figure out what it means. I think it means something isn't mapped correctly, but I cant figure out what. I am using the code first model, and I have an existing database that I want totally custom mappings for. Right now, I have everything in my classes named the same as my database to eliminate possible cuases.
The Exception is thrown when I try to .Add() the entity to the context.
The Entity as it is in the Database
The Entity in my DataLayer
public class EAsset
{
public int i_GID { get; set; }
public EAssetType Type { get; set; }
public EOrgEnvironment Environment { get; set; }
public EUser Contact { get; set; }
public string s_Name { get; set; }
public string s_Role { get; set; }
public DateTime d_Added { get; set; }
public DateTime d_LastUpdated { get; set; }
public bool b_Retired { get; set; }
public EAsset()
{
Type = new EAssetType();
Environment = new EOrgEnvironment();
Contact = new EUser();
d_Added = DateTime.Now;
d_LastUpdated = DateTime.Now;
}
}
The Context Object (with attempted table mapping and key assignment)
public class ScannerContext : DbContext
{
public ScannerContext()
: base("LabDatabase") { }
public DbSet<EAsset> EAssets { get; set; }
public DbSet<EAssetType> EAssetTypes { get; set; }
public DbSet<EOrgEnvironment> EOrgEnvironments { get; set; }
public DbSet<EUser> EUsers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<EAsset>().HasKey(k=>k.i_GID).ToTable("t_Assets");
modelBuilder.Entity<EAssetType>().HasKey(k => k.i_ID).ToTable("t_Asset_Types");
modelBuilder.Entity<EOrgEnvironment>().HasKey(k => k.i_ID).ToTable("t_Org_Environments");
modelBuilder.Entity<EUser>().HasKey(k => k.i_ID).ToTable("t_Users");
base.OnModelCreating(modelBuilder);
}
}
The Program
class Program
{
static void Main(string[] args)
{
EAsset Entity = new EAsset { s_Name = "jewri-pc" };
var sContext = new ScannerContext();
sContext.EAssets.Add(Entity);
sContext.SaveChanges();
}
}
For EF runtime version 4.0.3 / version 4.0
public class ScannerContext : DbContext
{
public ScannerContext()
: base("LabDatabase") { }
...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<ScannerContext>(null); // <--- This is what i needed
...
base.OnModelCreating(modelBuilder);
}
}
With that code installed I am now chasing errors related to having all my relationships accounted for in the model. The FK Constraints are forcing me to add the missing relational items.
Found info here. They explain the importance a bit.
The model backing the <Database> context has changed since the database was created
Enable-Migrations -ContextTypeName EmployeeProject.Models.DepartmentContext
Means you have to write your project name.Models.Context name
It will work.