Unity.MVC register autogenerated dbcontext from ef - entity-framework

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>();

Related

Entity Framework Migrations Command and Program.cs

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....

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

How to configure Domain Classes to use ObservableCollection using EF?

I have started using Entity Framework Code First modeling technique and have seen many examples of implementing one to many (1-N) relationship using DataAnnotation and FluentAPI but all examples are using ICollection while modeling domain classes. I have already used generic ObservableCollection in my domain classes and do not intent to change it.
Currently while specifying the configuration using FluentAPI, i am getting following error:
HasRequired(t => t.App)
.WithMany(t => t.EndPoints) // error here
.HasForeignKey(t => t.App);
Cannot implicitly convert Type 'EndPoints' to 'ICollection'.
Note: EndPoints class is implemented using ObservableCollection.
My question is how to make it work?
Following is my entity definition:
public class ModelBase
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class RuleApp : ModelBase
{
public EndPoints EndPoints { get; set; }
}
public class EndPoint : ModelBase
{
public RuleApp RuleApp { get; set; }
}
public class EndPoints : GenericObservableCollection<EndPoint> { }
public class GenericObservableCollection<T> : ObservableCollection<T>
{
// other common stuff handling
}
This is an Example to do that :
public class ModelBase
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class RuleApp : ModelBase
{
//This for create RelationShip
public virtual ICollection<EndPoint> EndPoints { get; set; }
[NotMapped]
Public EndPoints GenericEndPoints { get; set; }
public void TransferToGenric()
{
GenericEndPoints =new EndPoints(EndPoints)
}
}
public class EndPoint : ModelBase
{
public RuleApp RuleApp { get; set; }
}
public class EndPoints : GenericObservableCollection<EndPoint> { }
public class GenericObservableCollection<T> : ObservableCollection<T>
{
// other common stuff handling
}
If you use GenericObservableCollection as a Property EF Mapped all property in your calss, so I create just a property to use endpoint and after that i transform it to the GenericObserveableCollection.
in the constractor of you EndPoins class you have to featch all data in endpoint to do what you want

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; }
}

Entity framework - Invalid Object Name

I have a project where i use EF 4.1.
At Data Context:
public DbSet<Customer> Customer { get; set; }
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) { }
Entity model class:
[Table("User",SchemaName="dbo")]
public class User{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Once I run the application I was getting following error.
Invalid object name dbo.User
Why? What is wrong?
What is in your OnModelCreating method?
Try to remove default plural table name:
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
If you happen to be using configuration mapping (EntityTypeConfiguration) classes to define your tables, you'll get this error if you forget to attach the Configuration class for the table to the Model Builder.
In my case, it really stumped me for a bit, because I already had another table (SomeThing) working perfectly within this Context class. After simply adding a new table (OtherThing) where everything seemed to be setup identical to the first, I got the error: Invalid object name 'dbo.OtherThings.
The answer was in my Context class:
public DbSet<SomeThing> SomeThings { get; set; }
public DbSet<OtherThing> OtherThings { get; set; }
...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new SomeThingMap());
// OOPS -- Forgot to add this!!
modelBuilder.Configurations.Add(new OtherThingMap());
}
For reference, here's my SomeThingMap class:
public class SomeThingMap : EntityTypeConfiguration<SomeThing>
{
public SomeThingMap()
{
...
this.ToTable("SomeThing");
...
}
}
And my new OtherThingMap class:
public class OtherThingMap : EntityTypeConfiguration<OtherThing>
{
public OtherThingMap()
{
...
this.ToTable("OtherThing");
...
}
}
It's a long shot, but I hope this helps point someone else in the right direction, at least.