System.Data.SqlClient.SqlException: Invalid object name 'dbo.__TransactionHistory' - entity-framework

I get the error
"System.Data.SqlClient.SqlException: Invalid object name
'dbo.__TransactionHistory'."
when I try creating a new dbcontext using the TransactionContext in EF 6.1.3. It seems like a bug where it's using the transactioncontext API before the DBMigrator/Initializer even has a chance to create it since these operations are done within a transaction.
Below is the code that replicates the problem
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.SqlServer;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
new SomeDbContext().Database.Initialize(false);
}
public class Person
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
public class MyConfiguration : DbConfiguration
{
public MyConfiguration()
{
SetTransactionHandler(SqlProviderServices.ProviderInvariantName, () => new CommitFailureHandler());
}
}
[DbConfigurationType(typeof(MyConfiguration))]
public class SomeDbContext : DbContext
{
static SomeDbContext()
{
Database.SetInitializer(new DropCreateDatabaseAlways());
}
public SomeDbContext()
: base(#"Data Source=.;Initial Catalog=SomeDbContext;Integrated Security=True;MultipleActiveResultSets=True;Connect Timeout=1;")
{
}
public virtual DbSet People { get; set; }
}
}
}

I ended up doing two things.
Manually run the SQL CREATE TABLE [dbo].[__TransactionHistory] (
[Id] [uniqueidentifier] NOT NULL,
[CreationTime] [datetime] NOT NULL,
CONSTRAINT [PK_dbo.__TransactionHistory] PRIMARY KEY ([Id])
Creating a CommitFailureHandler that overrides the BeganTransaction to not call the base method until the table has been created

Related

issue with new create dbcontext class object in asp.net core 2.1

I m new in .net core 2.1
I m working with .net core 2.1 with code first approach
issue is when I create a new object dbcontext class then give error see below line
dbcontextstudent db=new dbcontextstudent(); //here give an red line
appsettings.json
},
"ConnectionStrings": {
"sqlserverconn": "Server=DEVISSHAHID; Database=studdbs; User id=xxxx;Password=xxxxx;"
},
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
//connection string
services.AddDbContext<DbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("sqlserverconn")));
student.cs
namespace WebApplication1.Models
{
public class student
{
[Key]
public int studid { get; set; }
public string studname { get; set; }
public string studsalary { get; set; }
public int studage { get; set; }
}
}
dbcontextstudent.cs
namespace WebApplication1.Models
{
public class dbcontextstudent : DbContext
{
public dbcontextstudent(DbContextOptions<dbcontextstudent> options) : base(options)
{
}
public DbSet<student> stud { get; set; }
}
}
HomeController.cs
I m not understood the above intellisense
I write the code as per intellisense but still give an error I know error is clear but not solved
which place doing I m wrong?
You will have to pass your DbContext type to the AddDbContext method in ConfigureServices method like this:
services.AddDbContext<dbcontextstudent>(options => options.UseSqlServer(Configuration.GetConnectionString("sqlserverconn")));
After that, you have registered the dbcontextstudent class in dependency injection.
You shouldn't create the instance of dbcontextstudent on your own like you did:
dbcontextstudent db=new dbcontextstudent();
Instead you can inject it though the constructor of your controller like this:
public HomeController : Controller
{
private readonly dbcontextstudent _db;
public HomeController(dbcontextstudent db)
{
_db = db;
}
... and then you can use the _db variable in your post action
}

Error comes as a {"Invalid object name 'dbo.TableName'."}

I'm using Entity Framework and MVC3,
I have used Model First approch...
I have used Company as a Base class and I have inherited the Lead Class from it.
When I run the application its gives an error...
This is Base Class
using System;
using System.Collections.Generic;
namespace CRMEntities
{
public partial class Company
{
public int Id { get; set; }
}
}
This is Lead Class (Child)
using System;
using System.Collections.Generic;
namespace CRMEntities
{
public partial class Lead : Company
{
public Lead()
{
this.Status = 1;
this.IsQualified = false;
}
public Nullable<short> Status { get; set; }
public Nullable<bool> IsQualified { get; set; }
}
}
I have added the controller,and in index view I have added this code...
public class Default1Controller : Controller
{
private CRMWebContainer db = new CRMWebContainer();
//
// GET: /Default1/
public ViewResult Index()
{
return View(db.Companies.OfType<Lead>().ToList());
}
}
This is DB and Model ...
Its giving the inner error -
{"An error occurred while executing the command definition. See the
inner exception for details."} {"Invalid object name
'dbo.Companies'."}
Do you have a Companies table or Company table in your database. It looks like you have a Mapping issue. Entity Framework will make some guesses as to how it pluralizes entity names by default.

seed method not called with EntityFramework CodeFirst

I've been struggling on and off with this problem since 4.1 (now I'm on 4.3). It seems to me that to get the seed method called, all I should have to do is the following:
1) Create an empty data catalog on sqlserver
2) Execute the code below:
Database.SetInitializer(new DropCreateDatabaseAlways<SiteDB>());
I have my SiteDB defined as follows:
public class SiteDBInitializer :
DropCreateDatabaseAlways<SiteDB>
{
protected override void Seed(SiteDB db)
{
... (break point set here that never gets hit)
I feel like I must be missing something very simple because this creates my tables, but does never calls the seed method.
To Make this more clear, here is a full example that includes all the code. When I run it, seed never gets called:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Data.Entity;
namespace ConApp
{
internal class Program
{
private static void Main(string[] args)
{
Database.SetInitializer(new SiteDBInitializer());
using (var db = new SiteDB())
{
var x = db.Customers;
}
}
}
public class SiteDB : DbContext
{
public DbSet<Customer> Customers { get; set; }
}
public class Customer
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
public string LastName { get; set; }
}
public class SiteDBInitializer :
DropCreateDatabaseAlways<SiteDB>
{
protected override void Seed(SiteDB db)
{
db.Customers.Add(new Customer() {LastName = "Kellner"});
db.Customers.Add(new Customer() {LastName = "Jones"});
db.Customers.Add(new Customer() {LastName = "Smith"});
db.SaveChanges();
}
}
}
You need call Database.SetInitializer(new SiteDBInitializer()); instead.
I looked at all the answers for that, nothing really works, and I wonder if that's a Microsoft bug for not calling the Seed method when DB does not exists.
The only code that worked, was to actually make the class call the seed if DB does not exists:
Context class:
class AlisDbContext : DbContext
{
public class MyContextFactory : IDbContextFactory<AlisDbContext>
{
public AlisDbContext Create()
{
return new AlisDbContext("CompactDBContext");
}
}
public AlisDbContext(string nameOrConnectionString) : base(nameOrConnectionString)
{
Database.SetInitializer(new AlisDbInitializer(this));
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<AlisDbContext>());
}
public DbSet<SavedCredentials> SavedCredentialses { get; set; }
}
Then AlisDbInitializer need to check and call the seed method like:
public AlisDbInitializer(AlisDbContext alisDbContext)
{
if (!alisDbContext.Database.Exists())
{
Seed(alisDbContext);
}
}

Schema invalid and types cannot be loaded because the assembly contains EdmSchemaAttribute

Getting the following error:
Schema specified is not valid. Errors:
The types in the assembly 'x, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null' cannot be loaded because the assembly contains
the EdmSchemaAttribute, and the closure of types is being loaded by
name. Loading by both name and attribute is not allowed.
What does this error mean exactly?
I'm trying to shoe-horn into my application an EF model from an existing database.
Before this application was based on CodeFirst and using the repository pattern but for the life of me I can't get this working.
Before I had:
public class BaseModelContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
}
But in a EF model-first scenario (one where tables already exist in the db), I had to remove these as it didn't seem to like having a repository pattern on DbSet properties.
So I stripped these out, and the repository can then use repository on the classes already defined on the .designer.cs context class (the EF model). This has the EdmSchemaAttribute set inside the generated code.
So how do I get my repository pattern to work in the model-first scenario? What does the above error mean exactly?
EDIT
Added new code:
public class BaseModelContext : DbContext
{
// public DbSet<Location> Locations { get; set; }
public BaseModelContext(string nameOrConnection)
: base(nameOrConnection)
{
}
public BaseModelContext()
{
}
}
public class VisitoriDataContext : BaseModelContext
{
public VisitoriDataContext()
: base("visitoriDataConnection")
{
}
}
public interface IVisitoriDataContextProvider
{
VisitoriDataContext DataContext { get; }
}
public class VisitoriDataContextProvider : IVisitoriDataContextProvider
{
public VisitoriDataContext DataContext { get; private set; }
public VisitoriDataContextProvider()
{
DataContext = new VisitoriDataContext();
}
}
public class VisitoriRepository<T> : IRepository<T> where T : class
{
protected readonly IVisitoriDataContextProvider _ctx;
public VisitoriRepository(IVisitoriDataContextProvider ctx)
{
_ctx = ctx;
}
public T Get(int id)
{
return _ctx.DataContext.Set<T>().Find(id);
}
}
public interface ILocationRepo : IRepository<Location>
{
IEnumerable<Location> GetSuggestedLocationsByPrefix(string searchPrefix);
}
public class LocationRepo : VisitoriRepository<Location>, ILocationRepo
{
public LocationRepo(IVisitoriDataContextProvider ctx)
: base(ctx)
{
}
public IEnumerable<Location> GetSuggestedLocationsByPrefix(string searchPrefix)
{
return Where(l => l.name.Contains(searchPrefix)).ToList();
}
}
The error means that you cannot combine code first mapping (data annotations and fluent API) and EDMX mapping (with EntityObjects!) for entity with the same name. These two approaches are disjunctive.
The rest of your question is not clear.
Btw. building mapping from existing database is called database first not model first.
Decorate the assembly containing the GILayerModel type with [assembly: EdmSchema] attribute.
In my case, I had a class that derived from an entity (code-first class) in another assembly, and I was adding an instance of this class to the DBContext:
in DBEntities project:
public class GISLayer
{
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int GISLayerId { get; set; }
[StringLength(200)]
public string LayerName { get; set; }
public List<GISNode> Nodes { get; set; }
}
in the second assembly:
public class GISLayerModel : DBEntities.GISLayer
{
public new List<GISNodeModel> NodesModel { get; set; }
}
and the cause of error:
[WebMethod]
public void SaveGISLayers(GISLayerModel[] layers)
{
using (DBEntities.DBEntities db = new DBEntities.DBEntities())
{
foreach (var l in layers)
{
if (l.GISLayerId > 0)
{
db.GISLayers.Attach(l); //attaching a derived class
db.Entry(l).State = System.Data.EntityState.Modified;
}
else
db.GISLayers.Add(l); //adding a derived class
SaveGISNodes(l.NodesModel.ToArray(), db);
}
db.SaveChanges();
}
}
So, I used AutoMapper to copy properties of derived class to a new instance of base class:
DBEntities.GISLayer gl = AutoMapper.Mapper.Map<DBEntities.GISLayer>(l);
if (gl.GISLayerId > 0)
{
db.GISLayers.Attach(gl);
db.Entry(gl).State = System.Data.EntityState.Modified;
}
else
db.GISLayers.Add(gl);
That solved the problem.

'Default values not supported error' when working with Entity Framework Code First and SQLServer Compact 4.0

I am trying both xunit and TestDriven.Net for testing, for database using SQL CE4. Here is the entity definition:
public class Product
{
private readonly ICollection<Inventory> inventories = new List<Inventory>();
private int id;
public virtual int Id { get; set; }
//public virtual string ProductName { get; set; }
public virtual ICollection<Inventory> Inventories
{
get { return inventories; }
}
}
public class ProductConfiguration : EntityTypeConfiguration<Product>
{
public ProductConfiguration()
{
HasKey(p => p.Id); //Id column of the product is an Identity column
Property(p => p.Id);
}
}
And here is the test method:
[Fact]
public void WhenProductAddedItShouldPersist()
{
var product= ObjectMother.Single<Product>();
productRepository.Add(product);
unitOfWork.Commit();
Assert.NotNull(productRepository.One(product.Id));
}
XUnit passes the method while TestDriven fails with the message - 'System.NotSupportedException : Default values not supported'.
Surprisingly- if I add another property to the entity (e.g. ProductName), TestDriven also pass. Could anyone give me some clue why this is happening?
I'm getting the same error and while searching I found this: http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/583c7839-22a4-460e-8665-3e5e3998a0d5
Looks like it's a known bug.