FAQ Database Discussion Community


Error “NullReferenceException” received when saving changes in EF6 for VB

vb.net,entity-framework,entity-framework-6,dbcontext
Here is the console app VB.NET code: Imports System.Data.Entity Imports System.Linq Imports System.Configuration Module Module1 Sub Main() Using db = New BloggingContext() Console.Write("Enter a name for a new Blog: ") Dim name = Console.ReadLine() Dim blogt As New Blog() With blogt .Name = name End With db.Blogs.Add(blogt) db.SaveChanges() Dim query...

Why is the seed method not being called?

c#,asp.net-mvc-5,entity-framework-6,dbcontext,seeding
I am coding a MVC 5 internet application and would like some help to execute the seed method to populate the database with some entities. Here is my DbContext code: public class CanFindLocationDatabaseContext : DbContext { public class SystemInitializer : CreateDatabaseIfNotExists<CanFindLocationDatabaseContext> { protected override void Seed(CanFindLocationDatabaseContext context) { } }...

Unit Testing a Put With Entity Framework

c#,.net,unit-testing,dbcontext,put
I am attempting to unit test a PUT Request by checking values. However, I run into one simple issue. I have a test context like such: class TestAppContext : ContextInterface { public DbSet<User> Users {get; set;} public DbSet<Request> Requests { get; set; } public TestAppContext() { this.Users = new TestUsersDbSet();...

ASP.NET Identity User ID to Int error Conversion failed nvarchar Value

c#,asp.net,entity-framework,asp.net-identity,dbcontext
My code was working fine but when i tried to make the User ID as Int rather then string by adding in application user and in all classes. The add-migration works fine but upon update-database i get the following error. Conversion failed when converting the nvarchar value '60b67a91-64e0-4dc7-a85c-abd9521a0b50' to data...

Is there a way to Include() all with dbcontext?

c#,asp.net-mvc,entity-framework,dbcontext,eager-loading
When querying a DbContext with eager loading, it is required to Include("Navigation") in order to populate Navigation Properties. However on some occasions I would like to simply Include all navigation properties for an entity. Is there a method for this, or a way to do it? I'm assuming you could...

eager loading with dbcontext and projection

c#,entity-framework,dbcontext
B"H We are converting our project from ObjectContext to dbContext. Our current problem is with the difference in how eager loading is handled. Example context public class Person { public virtual ICollection<Email> Emails { get; set; } public virtual ICollection<Post> Posts { get; set; } } public class Email {...

Running Async Calls with DbContext in Entity Framework

c#,.net,entity-framework,asp.net-web-api,dbcontext
I want to be able to run an asynchronous call as follows: [Route("doit"),ResponseType(typeof(MyModel))] public IHttpResponse PostAsyncCall(MyModel model){ //Code removed for simplicity Task.Factory.StartNew(() => asyncStuff(model.id); return OK(model); } private void asyncStuff(int id) { MyModel model = db.MyModels.find(id); //Do things here. Long call to other webservices/processing of data. Time intensive normally. User...

How do I access DbContext.Entry Method (TEntity) in my generic repository class?

c#,entity-framework,namespaces,dbcontext
This should be really obvious but for some reason I can't figure it out. So in my generic repository class I have an update method to update an entity: public void Update<TEntity>(TEntity entity) where TEntity : class, IBusinessEntity { try { if (entity == null) { throw new ArgumentNullException("entity"); }...

Entities class constructor renewed with every update of model

c#,entity-framework,dbcontext
This is not an error but I'm trying to see if there's a workaround for it. I am using database-first Entity Framework. And my connection string is decided at runtime. So the constructor for my Entities class is like this: public partial class Entities : DbContext { public Entities(string cs)...

Choosing specific DBContext according to database selected in multi-database MVC application

c#,asp.net-mvc,dbcontext
I am trying to build an ASP.Net MVC application which updates database values according to the database selected by user. How I am designing it is by creating 2 EF DB Models (Each representing a DB). Both DBs are basically having same table structures, just different data as each DB...

Include only those in a related ICollection with specific filtering

entity-framework,asp.net-mvc-5,dbcontext
I have a Bill model which has associated payments and readings associated with it as follows: public class Bill { [Key] public Int64 BillID { get; set; } ............. public virtual ICollection<Reading> Readings{ get; set; } public virtual ICollection<Payment> Payments { get; set; } } In my BillsController I have...

Using the same DbContext object across different controllers

c#,controller,asp.net-mvc-5,entity-framework-6,dbcontext
I am coding a MVC 5 internet application & have a question in regards to using the same instantiated DbContext object across different controllers. I am wanting to do this because i am retrieving some of the same data in different controllers, & the inbuilt caching feature of the DbContext...

Using DbContext.Set.Add() Wont add to Database

c#,entity-framework,asynchronous,dbcontext
I'm having trouble getting my repository to insert into my database. My Context: public class Context : DbContext { public Context() : base("MyDatabase") { } public DbSet<Appartment> Appartments { get; set; } public DbSet<Sensor> Sensors { get; set; } public DbSet<Measurement> Measurements { get; set; } protected override void OnModelCreating(DbModelBuilder...

Should I separate my application context from ApplicationDbContext used for identity?

c#,asp.net,entity-framework,dbcontext,asp.net-identity-2
In Visual-Studio 2013, when creating an ASP.NET project, it generates a file IdentityModels.cs that contains a class ApplicationDbContext, that inherits from IdentityDbContext<ApplicationUser>, which eventually inherits from DbContext. Should I keep this context only for account-related entities, and created a separate context for all the other entities in the application or...

Generic with lambda expression

c#,entity-framework,generics,lambda,dbcontext
I'm trying to create "some kind" of custom "DbContext" for very specific application which uses MongoDb. And I faced with one problem: How did DbSet know of DbContext existence? I mean, when I write public DbSet<Assignment> Assignments { get; set; } public DbSet<User> Users { get; set; } in my...

Dependancy Injected DbContext is empty after populating DbContext created with new (EF7, ASP.NET 5, vnext)

asp.net,entity-framework,dbcontext,asp.net-5,entity-framework-7
I am relatively new to EF7 and have heard that Dependency Injection of DbContexts into the Controller constructor is a good way to go about getting the DbContext for use within given Action methods. However, there are many situations where Dependency Injection is impossible (for example, accessing the Db in...

Unused results from Entity Framework database call

c#,entity-framework,msbuild,dbcontext,compiler-optimization
Any decent compiler should eliminate dead code, at least to a certain extent. However, I am curious how a compiler (specifically MSBuild) handles a situation like the following: // let's assume LazyLoadingEnabled = false; var users = db.Users.ToList(); // more code that never touches 'users' Since LazyLoadingEnabled = false, will...

Entity Framework code first: How to ignore classes

c#,entity-framework,poco,dbcontext
This is similar to questions here and here, but those are old and have no good answers. Let's say I have the following classes: class HairCutStyle { public int ID { get; set; } public string Name { get; set; } } class CustomerHairCutPreference { public int ID { get;...

Get the key of an unknown entity [duplicate]

c#,entity-framework,primary-key,state,dbcontext
This question already has an answer here: Get the primary key value of an arbitrary entity in code first 1 answer Hello I would like to get the primary key value. public static void Look(LEBAEntities db, object obj) { // if getPrimaryKey(obj) == 0 db.Entry(obj).State = EntityState.Added; // else...

Entity Framework relationships between different DbContext and different schemas

c#,entity-framework,foreign-keys,repository,dbcontext
So, I have two main objects, Member and Guild. One Member can own a Guild and one Guild can have multiple Members. I have the Members class in a separate DbContext and separate class library. I plan to reuse this class library in multiple projects and to help differentiate, I...

How reuse an existing DbContext as base class for a new project?

c#,entity-framework,asp.net-mvc-5,dbcontext
I have an existing DbContext class that I want to use as a base class for my other web projects. That DbContext contain a really complete table structure to registrer companies and peoples with related information’s. When starting a new project, I do not want to create the same structure...

ConnectionString for ObjectContext in MVC raised Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON' error

c#,entity-framework,dbcontext,objectcontext
I'm working on an MVC application which uses ObjectContext (not DbContext) with EDMX file. As we know ObjectContext connection string is quite different from regular ADO.NET connection string. Here is the connection string I see in the application <add name="AuthorEntities" connectionString="metadata=res://*/Models.AuthorEntities.csdl|res://*/Models.AuthorEntities.ssdl|res://*/Models.AuthorEntities.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=ServerAddress;database=Author;user...

Calling SaveChanges when database objects have not been changed

c#,asp.net-mvc-5,entity-framework-6,dbcontext,savechanges
I am coding a MVC 5 internet application with EF6 and I have a question about what happens when the context.SaveChanges() method is called. Does the DbContext object store the CRUD actions that occur, such that if the SaveChanges() method is called, and none of the data in the database...

Entity framwork .ToList() is slow? (Query all)

c#,entity-framework,dbcontext
public List<Employee> GetEmployees(){ var employee = new ApplicationDBContext().Employee; return employee.ToList(); } //somewhere in other part of code. //Use GetEmployees. var employees = GetEmployees(); var importantEmployees = employees.Where(e => e.IsImportant == true); In terms of performance, this method is feasible? Is there any solution to make it fast? Thanks!...