FAQ Database Discussion Community


EF6: Schema specified is not valid; ambiguous mapping

c#,entity-framework,entity-framework-6,mef
I am using EF6 with the database first approach. The database has three simple tables: Person, Token and Template For the database I have generated the edmx model and entities Person.cs public partial class Person { public Person() { this.Tokens = new HashSet<Token>(); } public long Id { get; set;...

Entity Framework 6 Create model from existing table

c#,.net,entity-framework,entity-framework-6
We have to maintain a very old application. There is an old part (all data access is handled with stored procedures) and since my predecessors took over the application, they started to build a new part for the new requirements which uses entity framework 6. Now the customer has a...

How to limit the properties needed for the view from the model

vb.net,asp.net-mvc-5,entity-framework-6
I am working very hard to understand the concept of Entity Framework and Models by building a new MVC Architecture Solution. I have started only with two Models that are identical to an (EXISTING DATABASE - That I must model after [Maybe comeback and re-factor later]), with a lot more...

Entity Splitting and How to Configure the Join

c#,entity-framework,entity-framework-6
I have two tables. CREATE TABLE [dbo].[BusinessUnit]( [BusinessUnitId] [int] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](50) NOT NULL, [CurrencyId] [int] NOT NULL); CREATE TABLE [dbo].[Currency]( [CurrencyId] [int] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](35) NOT NULL, [Country] [nvarchar](50) NOT NULL, [Code] [nvarchar](50) NOT NULL); I have an Entity public class BusinessUnit { public int...

Code First Entity that doesn't include some required columns?

c#,sql-server,entity-framework,ef-code-first,entity-framework-6
I'm trying to use EF6 Code First to map Domain Entities to a legacy SQL database. I do not have access to modify the schema of the database or create stored procedures. The table I'm trying to map contains a few required columns that I don't want cluttering up my...

Need to fetch Oracle RAW in C# string datatype “as is”

c#,oracle,entity-framework-6
Help me out, requirement is that I need the same value of Oracle RAW to be in C# as a string. I am able to save String as RAW value in oracle table, but while fetching it is giving exception "Object must implement IConvertible" which I can understand that since...

Entity Type 'AstNode' has no key defined

asp.net-mvc-5,ef-code-first,entity-framework-6
I'm porting a data model from EF4 to EF6 Code First. I'm getting the following message when the database creation is attempted. I'm at a loss to understand what is causing this. I don't have any Context, AstNode or JSParser entities. It is also not looking in the Models namespace:...

Passing a query directly through LINQ to the db

c#,linq,entity-framework,entity-framework-6
I am currently converting functions in the DAL of an old app to a new app using Entity Framework/LINQ in its DAL. There are some instances where I would like to directly pass a string of sql to the database. Is this possible when using LINQ? Here is what I...

EF Code first - many to many relation mapping table with extra columns

entity-framework,ef-code-first,entity-framework-6,code-first-migrations
I am having a User Model and and a Group Model. User and Group share a many to many relationship. In when I translate this to table, I want to have a mapping table. I am using the following to achieve this. modelBuilder.Entity<UserGroup>() .HasMany(a => a.Users) .WithMany(b => b.UserGroup) .Map(mc...

Entity Framework Automatic migration

c#,entity-framework-6
I have a 3-tier architecture project (Web, Service, DataAccess), I just want to migrate the database to latest version whenever POCO changes happen. We can do this by calling the automatic migration code from Application_Start event. In this scenario, I don't have the reference of the DataAccess project in my...

Set collection to modified Entity Framework

c#,entity-framework-6
How can I set a collection to modified in the same way that I would do _context.Entry(thing).Property(x => x.MyProperty).isModified = true; like: _context.Entry(thing).Collection(x => x.MyCollection).isModified = true; EDIT: The purpose of this, is that my collection is a list of objects stored in a lookup table. I will only have...

Add Table in Existing Code First Database Approach

entity-framework-6,code-first
I have created 10 Tables in SQL server now using code first approach I have added 5 tables in my project. Based on this 5 tables it created 5 class in my project and then I completed my code of insert, update, delete and it work perfectly. Now I want...

Understanding ASp.net Identity key points

asp.net-mvc-5,entity-framework-6,asp.net-identity-2
I am an Asp.net developer but very much new to the Asp.net Identity framework. I have been studying the sample application and followed some tutorials too on Identity but still I am not able to grasp the concept completely. I have very firm grip over Asp.net membership but Identity seems...

Unable to get entity framework to generate a DbUpdateConcurrencyException (Database First)

c#,sql-server,entity-framework,entity-framework-6
I'm trying to implement the optimistic locking model for EF. I have a column with the timestamp datatype on the tables I'm trying to do this with. I've tried adding the Timestamp attribute on the member by modifying the T4 script. Running my test and seeing it not working, I...

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) { } }...

EF6 proxy's reference is sometimes null when entity's IValidatableObject.Validate method is called

entity-framework,entity-framework-6,nullreferenceexception
An EF6 proxy has a reference that is sometimes null when my entity's IValidatableObject.Validate method is called by the DbContext's SaveChangesAsync method. Running the same exact code multiple times results in different behavior. If I check my stock's Sku property (i.e. stock.Sku == null) outside of the Validate method it...

Catch concurrency exception in EF6 to change message to be more user friendly

c#,asp.net,.net,entity-framework,entity-framework-6
I am using EF6.1 and i would like to change the message to a more system specific message when the below exception is thrown. Store update, insert, or delete statement affected an unexpected number of rows (0) Now, my problem is i cannot seem to catch the exception? I have...

Entity Framework Error Deleting Entity with Foreign Key Relationship

entity-framework,entity-framework-6,poco
I am having a problem deleting some entities due to a foreign key relationship. I understand the following error message and have been doing everything I can think of to delete the entities without incurring this error: The DELETE statement conflicted with the REFERENCE constraint "FK_QuizUserAnswer_QuizWithQuestion". The conflict occurred in...

Code First Entity Framework 6: 1 to 1 with composite key

entity-framework,ef-code-first,entity-framework-6,ef-fluent-api
I've inherited a legacy SQL database that I am attempting to reverse engineer into Code First. Changing schema is not an option due to legacy software running on current config. What's strange to me is the developer configured the child table to have a composite primary key consisting of a...

Code based DB migration in Entity Framework 6.1.2: How to avoid using powershell commands?

c#,entity-framework,entity-framework-6,database-migration
I am using EF 6.1.2, to do Code based DB migration there are some commands we need to excecute. Which are: Add-Migration and Update-Database. I want this migration to happen in production environment. So is there any way to avoid Update-Database command in Package Manager Console and use C# APIs...

Remove/adding from virtual collections memory usage

c#,ef-code-first,out-of-memory,entity-framework-6
From what I can tell when profiling the sql, it executes a sql statement to retrieve all users for the group when it calls group.Users.Remove(user). Users is a virtual collection on the group, using Entity Framework 6 code first. var usersToRemove = Context.users.Where(u=>someListOfIds.Contains(u.Id)); //might only be a few users foreach(var...

DbSet.Attach(entity) vs DbContext.Entry(entity).State = EntityState.Modified

c#,entity-framework,entity-framework-6
When I am in a detached scenario and get a dto from the client which I map into an entity to save it I do this: context.Entry(entity).State = EntityState.Modified; context.SaveChanges(); For what is then the DbSet.Attach(entity) or why should I use the .Attach method when EntityState.Modified already attaches the entity?...

What's the proper way to get data using Entity Framework so you can navigate through objects?

c#,asp.net-mvc-5,entity-framework-6
I have a .Net 4.5 MVC 5 database first project that I'm playing around with. There's a data access layer (Entity Framework 6), a business logic layer and the MVC layer. If I have an object with relationships in the data layer: namespace DataAccess { public class Course { public...

Emit DbContext.OnModelCreating on every context creation

c#,entity-framework,entity-framework-6
I use entity framework code first to work with my database. I have several tables with different names but same structure, and this tables dynamically appears in database. How could I map EntityFramework to one of that tables at run-time and use data from just like I work this over...

How to make it explicit in Web API 2 for Entity Framework to only add parts of the object that have changed?

c#,asp.net,entity-framework-6,asp.net-web-api2
I'm using ASP.NET WebApi 2 and loading in part of a relational database structure into the front end website. This allows the user to make changes to multiple tables in a single store and to also view some extra data. This mostly works pretty well. It means I can store...

c# - Entity Framework ConnectionString won't update after changing App.Config in runtime

c#,entity-framework,entity-framework-6,connection-string,app-config
I'm developing a WPF application which depends on Entity Framework for data access. At the first time installation I need to create a new connection string based on the User input, then updating App.Config according to that. The problem is: after updating the App.Config file, Entity Framework doesn't detect the...

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

How do I construct a function that allows me to pass in several includes for EF via params?

c#,.net,entity-framework,entity-framework-6
I'm writing an EF-backed repository that has a concept of packages associated to each entity type that does .Include for its commonly used children. For example, I have a function that looks like this private static IQueryable<Foo> GetFooPackage(Entities context) { return context.Foo .Include(target => target.Bar) .Include(target => target.FooBar) } This...

Asp.Net MVC and Strategy pattern

asp.net-mvc,entity-framework-6,repository-pattern,strategy-pattern
I have an MVC application that uses Entity Framework. I am using a repository, unit of work and unity as dependency injection. The problem I have is that I have different authentication types, and each type I want a different class, so I decided to use the Strategy pattern public...

Renaming Identity tables with EF6 Migrations Failing

sql-server,asp.net-mvc,entity-framework,entity-framework-6
I'm trying to rename my Identity 2.0 tables via the Migrations tool in EF6/Package Manager. However, it's blowing up a part of the way through. I'm simply calling the following piece of code after the "ApplicationDBContext Create" in IdentityModels.cs: protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<IdentityUser>().ToTable("Users"); modelBuilder.Entity<IdentityRole>().ToTable("Roles"); modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles");...

ViewModel “no key defined” error

c#,asp.net-mvc-5,entity-framework-6
I've recently been learning asp.net MVC 5 and EF6 and i've started to develop viewmodels for my views instead of stuffing values into the viewbag. I this is my viewmodel called EmployeeCreate namespace Rota.ViewModels { public class EmployeeCreate { public string FirstName { get; set; } public string LastName {...

The difference between EF6 and EF4.1 in files hierarchy

c#,entity-framework,visual-studio-2012,entity-framework-6,edmx
I'm a beginner to Entity Framework . I notice that When I use EF6 with Visual studio 2013: I have .Designer.cs empty file with this comment: // T4 code generation is enabled for model 'C:\Users\Luka\Desktop\Test\EF-db2008\AdventureWorks\AdventureWorksLib\AdventureWorksLib\AWLTModel.edmx'. // To enable legacy code generation, change the value of the 'Code Generation Strategy' designer...

how can i check return value of stored procedure in entity framework

c#,stored-procedures,entity-framework-6
I have a stored procedure call but i want to get the return value of the stored procedure. Return type is integer. Following the code where I am calling the stored procedure else if(ReportName=="LandMarkInOutReport") { _DBContext.LandMarkInOutReport(report.ReportParameters.StartDate, report.ReportParameters.EndDate, Convert.ToInt64(paramArr1[3]), Convert.ToInt32(paramArr1[9]), Convert.ToInt32(paramArr1[11]), paramArr1[5], paramArr1[7]); } So please guide me how can I...

Should I seed DB in DropCreateDatabaseIfModelChanges or in DbMigrationsConfiguration?

c#,entity-framework,ef-code-first,entity-framework-6,code-first-migrations
I have a working code first entity model with a model change policy in place: public class MyModelChangePolicy : DropCreateDatabaseIfModelChanges<MyDBContext> { protected override void Seed(MyDBContext context) { //Add the enumeration type values context.SyncEnums(false); base.Seed(context); } } SyncEnums is an extension method I created which loads data into several enumeration type...

Ordering missing in entity framework query

c#,entity-framework,entity-framework-6
I have the following C# code generating a query on a sqlserver. return c.Bags .Where(b => b.RollformerId == RollformerId && (!b.Order.OnHold.HasValue || b.Order.OnHold.Value == false) && (!b.Order.Archive.HasValue || b.Order.Archive.Value == false) && (!b.Order.Inactive.HasValue || b.Order.Inactive.Value == false) && (b.BagStatus.BagStatusId == notStarted || b.BagStatus.BagStatusId == inProgress)) .OrderBy(b => b.Priority) .ThenBy(b =>...

ObjectContext is disposed, can not longer used

c#,asp.net-mvc-3,entity-framework-6
Example Code: private static list; public void SetList () { var query = Container.Advices.Where (); list= query.ToList(); } public void doStuff () { var temp= list.where (...).ToList (); } problem situation: When i call the first time SetList, all worked fine. Now, a second is SetList called. I can see...

Entity Framework 6: Schema specified is not valid

c#-4.0,entity-framework-6,.net-framework-version
I have 4 following projects in my solution. All the projects use target framework version 4.0. 1. Durabuilt.CantorERP.Entities > Class library project > Used ADO.NET Entity Data Model to expose tables and views in SQL Database named CantorERP 2. Durabuilt.Duranet2.Entities > Class library project > Used ADO.NET Entity Data Model...

Cannot Eager Load Entity Framework Child Entities

c#,entity-framework,entity-framework-6
I have implemented a UnitOfWork style method of working and I cannot seem to force an eager load in EntityFramework 6. Every time I use the "Include()" syntax it seems to be ignored and the SQL generated will not carry out any form of join which is resulting in a...

IronPython entity framwork 6 Could not find attribute where

.net,linq,entity-framework,entity-framework-6,ironpython
I have successfully integrated entity framework into my project. I'm also able to read data from a table over my dbcontext. But when i try to use the linq where method, i get the following error message: 'DbSet[Workflow]' object has no attribute 'Where' This is my code: import clr import...

Mixing automatic and explicit migrations on the production environment

entity-framework,entity-framework-6,code-first-migrations
I've seen this question, and I'm wondering how automatic migrations mixed with explicit migrations would be applied on the production environment. Let us say I create migrations in the following order: Explicit Migration A Explicit Migration B Automatic Migration C Explicit Migration D Since no file is created for the...

How to atomic increment when row might not exist?

c#,.net,entity-framework,entity-framework-6
Suppose I have MyContext derived from DbContext with a DbSet<Item> Items, where Item is defined as follows. public class Item { [Key] public string Key { get; set; } [ConcurrencyCheck] public int Value { get; set; } } Given a key, I want to atomically increment the corresponding value, where...

How to Improve SQL Azure Query Performance

tsql,entity-framework-6,sql-azure,query-performance
I am using EF 6 to execute a SqlQuery, which is a SELECT statement returning 47 columns with a max of 500 rows. The query has eight LEFT JOIN statements. In my local environment, the query only takes around 300 ms, as indicated in Express Profiler. On SQL Azure, the...

A member of the type, 'PropertyName', does not have a corresponding column in the data reader with the same name

c#,ef-code-first,entity-framework-6
I'm using Entity Framework 6, code first, and using the ObjectContext.Translate() method to execute a stored procedure to fill a list of objects. Do I need to return every property of the class in the stored procedure? Or can I return some properties? The MSDN article Directly Executing Store Commands...

EF 6 interceptor to set connectionstring

entity-framework,ef-code-first,entity-framework-6
How can I use EF6 interceptors to dynamically set the connection string for a db context? I am using code-first to work with the database. Basically in my application I have this scenario: In my app.config file I have defined 3 database connection strings: <connectionStrings> <add name="Db1DbContext" connectionString="Data Source=***;Initial Catalog=***;Integrated...

Inserting or adding a string to a database table using linq to SQL and EF6?

entity-framework-6
I'm trying to learn LINQ to SQL and Entity Framework 6. Just trying to add strings to a database table. Here is what I've got for now: static void Main(string[] args) { using (ResponsesEntities db = new ResponsesEntities()) { try { Respons res = new Respons(); res.ExtSerial = "ASDF1234"; res.Date...

Circular and external references in EF 6 entities

c#,.net,entity-framework,entity-framework-6
I have two models: class Site { public virtual string Name { get; set; } public virtual Page RootPage { get; set; } } class Page { public virtual string Name { get; set; } public virtual string Content { get; set; } public virtual Site ContainingSite { get; set;...

Converting string to datetime in mapping to viewmodel

c#,asp.net-mvc,datetime,entity-framework-6
I have an MVC app where I collect DateTime fields (MM/dd/yyyy) as strings to avoid Chrome overriding the datepicker in bootstrap and to avoid mapping in sqlbulk upload of Excel. I now need to map this string field back to datetime and am struggling with this greatly. Here's my Model:...

Fluent mapping and relation table with Active flag

c#,entity-framework,entity-framework-6
I have a relation table but with one additional column Active bit not null I fail to understand how I should map with in EF6, I have 3 tables, Foo, Bar and FooBar where FooBar is the relation table FooBar { FooId: int (Key and FK) BarId: int (Key and...

Entitiy Framework code-first migrations in multiple development environments

sql-server,entity-framework-6,code-first-migrations
I'm working on a project that uses EF6 with code-first migrations. All the work till now was done on a Dev. environment, including the DB migrations. I need to deploy the code to another environment (QA), however I've stumbled into a problem: The DB exists, however there are no tables...

Dynamic connection string to Web Api

asp.net-web-api,entity-framework-6,connection-string
I am exposing my repository operations through web api. Repository has been implemented with Entity framework and Unit Of Work Pattern. I have many instances of the same database. Each one represent the data of a different Client. Now the issue is how can I set the connection string dynamically...

How do I construct a DbContext from an ObjectContext?

c#,entity-framework,ef-code-first,entity-framework-6,xaf
I am trying to create a constructor for my Context class from an ObjectContext. I want to do this because I am using DevExpress xaf which makes it easy to get hold of the ObjectContext from inside a view. The MSDN help is here but it does not include an...

Updating EF6 edmx model causes new model file to be created

c#,sql-server,vb.net,entity-framework,entity-framework-6
I'm using EF 6.1 with the downloaded T4 template from VS. When I try to update the EF model with new information, or just issue a refresh from my database, the model file duplicates and I get a massive amount of errors. So, for example, my model file is called...

Navigation Properties using two foreign keys

entity-framework,asp.net-mvc-5,entity-framework-6
I have a project with several tables in the same database. public class UserImage { [Key] public int Id { get; set; } public string OwnerId { get; set; } [ForeignKey("OwnerId")] public virtual ApplicationUser Owner { get; set; } //some fields are removed for brevity } public class FriendRequest {...

How can I force EF to use joins instead of splitting up a complicated query?

c#,entity-framework,entity-framework-6,iqueryable,deferred-execution
I have a complex IQueryable that I would like EF to populate with a single database query so that I can use it with deferred execution. Please consider the following example. For these models: public enum AlphaState { Unknown = '\0', Good = 'G', Bad = 'B' } [Table("MY_ALPHA")] public...

Distribute entity framework models over different assemblies

c#,.net,entity-framework,model,entity-framework-6
Currently i am trying to use entity framework 6.3 with a kind of distributed models. My problem is, i want to seperate the models in different assemblies (for example the core application and plugins). Now i'm search for a way, that my application get all models over reflection or some...

Entity Framework Serialize entity to json with included related entities

json,entity-framework-6
I have a User entity with too many relations to other entities in the system. And I am using AngularJs and want to serialize the User entity to json with only the included entities. Here is my select statement: var users = unc.Users.Include("Profile").ToList(); when serializing this to json it will...

What is the simplest way to implement an Entity Framework 6 Add-or-Update method

c#,database,entity-framework,entity-framework-6
I have a project that uses Entity Framework 6 that does an Add-or-Update (i.e. Upsert) for a bunch of different entity types. For each of these entities, there is an surrogate integer ID (i.e. primary key), a natural key (e.g. customer ID) used for external lookups, and a set of...

ASP - EF 6 bind only certain properties of a complex list?

asp.net-mvc-5,entity-framework-6
I have a view that creates one main object (Author) and a list of other objects for it (Books). So the created object can return the books by calling author.Books.ToList() for example. My problem is that I only want users to be able to set certain attributes of the book...

Entity Framework connection factory not working

c#,entity-framework,connection,entity-framework-6,sqlanywhere
I use entity framework 6 and try to overwrite the connection string factory. I've written the following connection factory: internal class MyDBConnectionFactory : IDbConnectionFactory { public System.Data.Common.DbConnection CreateConnection(string nameOrConnectionString) { SAConnection connection = new SAConnection(ConnectionManager.GetConnectionString(nameOrConnectionString ?? "Default")); return connection; } } Than i have written my own configuration class: public...

Integration testing the entity framework - separate the seed method call only for PROD -

entity-framework,entity-framework-6,integration-testing
I want to integration test my repositories. I want to setup and insert test data before each integration test method. Then I want to execute my repository logic Then I want to assert that the logic works by returning the correct data from the database. I do not want to...

Using SqlQuery> in Entity Framework 6

c#,.net,entity-framework,dictionary,entity-framework-6
I'm trying to execute a SQL query in EF 6. The select query returns two string columns, e.g. select 'a', 'b', and can have any number of rows. I'd like to map the result to a dictionary, but I can't get ride of the following error. Error 1 Cannot implicitly...

How to register per request dependencies using StructureMap, MVC 5, and WebApi 2?

asp.net-mvc-5,entity-framework-6,asp.net-web-api2,structuremap
I have a Mvc5-WebApi2 application that uses StructureMap for dependency injection using the StructureMap.Mvc5 and StructureMap.WebApi2 Nuget packages. I want to register my EF 6 DbContext with HttpContext lifecycle for both MVC and Web controllers. Can someone point me to a succinct explanation on how to achieve this for both...

dbcontext.entity.select not available in Visual Studio 2013

c#,asp.net,sql-server-2012,linq-to-entities,entity-framework-6
it's been a while since I work with EntityDataModel. I used to do things like: var listaProductos = dbContext.Productos.Select(p => new I just started a new web project with asp.net and added the entity data model but If i try to do the same as the example above I can't...

Updating records using a Repository Pattern with Entity Framework 6

c#,asp.net-mvc-5,entity-framework-6,asp.net-identity,repository-pattern
I'm writing a simple blog application and trying to establish CRUD operations in my generic repository pattern but I'm getting an error on my update method that says: 'System.Data.Entity.DbSet' does not contain a definition for 'Entry' and no extension method 'Entry' accepting a first argument of type 'System.Data.Entity.DbSet' could be...

sp_executesql output parameter incorrect value

sql-server,entity-framework-6
I'm getting different result for outputParam from fallowing two queries. The first one is generated by entity framework and it gives 0 for outputParam. For the second result is 5. declare @p2 int set @p2=0 exec sp_executesql N'usp_GetOrders @order_date, @output_param',[email protected]_date datetime,@output_param int output',@order_date='2015-05-07 12:37:14.579',@[email protected] output select @p2 AS outputParam declare...

How to check the model against DB schema at startup

entity-framework-6,code-first
I have a caching database which can simply be dropped and re-created if there are missing new fields in the schema. I can't be bothered with Migrations, it always bugs me. So how do I perform this startup check? db.Database.CompatibleWithModel returns true, but running a Linq query against a mismatched...

EntityState.Deleted are removing items from my List

entity-framework,entity-framework-6
When I set db.Entry(episode).State = EntityState.Deleted EF removes episode from my List and throws a collection was modified enumeration operation may not execute. Here is my code: public async Task UpdateAsync(List<Episode> episodes) { using (var db = new DbContext()) { var serie = await db.Series.Include(s => s.Episodes).SingleOrDefaultAsync(s => s.Id ==...

Create a computed field using Entity Framework 6

c#,entity-framework,entity-framework-6
Consider the following model for a EF 6 entity: Id (int, nullable:false, identity: true) Name (string) Number (string). I want number to persisted as combination of letter and id field. For example if during insert id valuse is going to be 1, I want number to be A00000001. I tried...

Entity Framework Code First - Optional/required two-way navigation

entity-framework,ef-code-first,foreign-keys,entity-framework-6,foreign-key-relationship
I have a code first model similar to the following: public class TestContext : DbContext { public DbSet<Class1> Class1s { get; set; } public DbSet<Class2> Class2s { get; set; } } public class Class1 { public int Class1Id { get; set; } } public class Class2 { public int Class2Id...

Entity Framework adding additional incorrect link to self referring many to many link [duplicate]

entity-framework,entity-framework-6
This question already has an answer here: Entity Framework 4.1 Code First Self-Referencing One-to-Many and Many-to-Many Associations 1 answer I have a table which links to itself in a many to many self join. The tables are created correctly but Entity Framework is adding an additional Entity_ID field in...

What database systems are fully supported by Entity Framework 6 and/or 7?

entity-framework,entity-framework-6
Which database systems (relational or NoSql) are supported by Entity Framework 6 and/or 7?

Calling an async method from the database seed method

c#,asynchronous,asp.net-mvc-5,entity-framework-6,initializer
I am coding a MVC 5 internet application and would like to know how to call an async method from the seed method when a database is created. Here is my code: public class ApplicationDbInitializer : CreateDatabaseIfNotExists<ApplicationDbContext> { protected override void Seed(ApplicationDbContext context) { SetupAdminAndSampleObjectsDatabase(); base.Seed(context); } } Currently, when...

Property Is Required on Update EF6

c#,asp.net,.net,entity-framework,entity-framework-6
I have a property that is required on my entity. Upon adding the entity to the database, that property is populated by the system. From here on, this property should never be changed. This property is also never passed to the client. So now when the user edits this entity,...

How to get tables from database first approach without .tt and edmx files?

c#,asp.net-mvc,entity-framework,entity-framework-6
I am working on database first approach. I followed the following link https://msdn.microsoft.com/en-us/data/jj200620 I'm able to get the cs files. But cs file are coming under edmx folder. but I want to get cs file directly as similar as code first approach I am using entity framework 6 and mvc...

Autofac: How do you register a generic with multiple type arguments? Registering IGenRepo with EFGenRepo

c#,entity-framework-6,autofac,asp.net-mvc-5.2,.net-4.5.2
I am trying to build a generic repo and use autofac for testing. I have the following interface: public interface IGenRepo<T, TKey> where T : class { IQueryable<T> Items { get; } T find(TKey pk); RepoResult delete(TKey pk); RepoResult create(T item); RepoResult update(T item); RepoResult save(); } And here is...

How to completely reset all Entity Framework 6 migration history? (Zombie migrations!)

.net,entity-framework-6,code-first-migrations
Short version: After deleting the entire database (including __MigrationHistory) AND all the migrations in the solution... somehow, named migrations are being found somewhere and applied by DbMigrator! Where are they coming from??? Long version: We are using Entity Framework 6, against SQL Server 2012. It's an MVC webapp, and we...

What's the equivalent to not using params with Expression>[]?

entity-framework-6,func
I have some code in a repository base class for Entity Framework that eager loads Navigation properties: public virtual List<T> Find(Func<T, bool> where, params Expression<Func<T, object>>[] navigationProperties) { //blah biddy blah blah } Then when calling the above method: var beers = BeerRepository.Find(x => x.Type == "IPA", a => a.Ingredients,...

Unable to cast code first

c#,entity-framework,entity-framework-6,code-first
Having this class that represents model public class User : IHaveId { public User() { Operations = new Collection<Operation>(); } public int Id { get; set; } public string UserName { get; set; } public string CardNumber { get; set; } public string Pin { get; set; } public double...

Get name of all available classes under model.tt : Entity Framework 6

c#,entity-framework-6,complextype
I want to get all available classes name those are listed under Model.tt. I have tried below piece of code to get them but that is giving only table name not complex types which are imported via stored procedure: var x = ((IObjectContextAdapter)d).ObjectContext.MetadataWorkspace.GetItems<EntityType>(DataSpace.CSpace); // d is my context object. I...

Can I map a protected ICollection using EF6 code first mappings?

c#,entity-framework,entity-framework-6
Given the class: public class User { public int Id { get; protected set; } protected virtual ICollection<Role> UserRoles { get; set; } public IEnumerable<Role> Roles { get { return new ReadOnlyCollection<Role>(UserRoles.ToArray()); } } } How can I map the the UserRoles using EF6 code-first mappings? I don't want to...

Selecting list of object type after grouping in linq

c#,linq,entity-framework,entity-framework-6
I have a table such as the following: ProductId, CategoryId 123, Category1 123, Category2 123, Category1 My parameter is productId and I need to return a list of type Category based on distinct categories for the given productId in the above table. ...

Inner join with join table to retrieve all CategoryProducts in linq

c#,linq,entity-framework,entity-framework-6
I have a join table called CategoryProducts with 2 fields (CategoryId, ProductId). I am trying to figure out the correct way to get all product objects within a category. Here is what I have: // get list of all of the products in a category public static IEnumerable<Product> GetList(int categoryId)...

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

ObjectContext instance has been disposed error

c#,entity-framework-6
I am new to EF and I have the following query: List<Test.MemberAccount> userAccounts = new List<Test.MemberAccount>(); using (var context = new CoopEntities1()) { var query = from s in context.MemberAccount join sa in context.AccountType on s.account_type_id equals sa.id where s.member_guid == memberID select s; userAccounts = query.ToList(); } return userAccounts;...

Opening and closing connections to SQL Server

c#,entity-framework-6
I am working in a small team of about a dozen developers on a project being written in C# WPF as the infrastructure/dba. As I run traces against the SQL Server to see how performance is going, what I am seeing is a constant: open connection run some statement close...

Update Model from Database reverts manual changes made to .context file

c#,.net,sql-server,entity-framework,entity-framework-6
we recently updated from EF4 to EF6, then I read about .context.tt and .tt files. Added them to the system things look fine but System.Data.Object was to be changed to System.Data.Entity.Core.Object I thought this would be one time effort but everytime we update model from database, we have to rename...

C# How to SELECT row n in EF6 [duplicate]

c#,sql-server,select,entity-framework-6
This question already has an answer here: Linq selecting range of records 3 answers How can I tell EF6 that I want the Second Row, or the 5th Row, or the N'th Row? The Id of the rows are not sequential in that there are gaps as rows are...

Error while connecting to database in code-first Entity Framework

c#,ef-code-first,entity-framework-6
I am getting following error message when context is trying to connect to database using code-first approach of Entity Framework System.Data.Entity.DbContext' does not contain a definition for 'System' and no extension method 'System' accepting a first argument of type 'System.Data.Entity.DbContext' could be found (are you missing a using directive or...

Setting navigation property in code is giving me a null reference exception [duplicate]

c#,asp.net,linq,entity-framework,entity-framework-6
This question already has an answer here: What is a NullReferenceException and how do I fix it? 17 answers When I create a new object of type OrderDetail like this: OrderDetail orderDetail = new OrderDetail(); And then try to set one of its reference properties like this: OrderDetail.Material.Description =...

Database object with different data

sql,asp.net,asp.net-mvc,database,entity-framework-6
I'm making a web page in ASP.NET MVC which compares prices from different shops. I have a one-to-many with products and the shops, where the SHOP has one PRODUCT and a PRODUCT has many SHOPs, the problem is that the product is the same but the price is different. Example:...

Setting schema name for DbContext

c#,entity-framework,entity-framework-6,database-schema
I know how to set the schema for a table in my context but is there a way to set the default schema for all the tables in a context? i.e. [Schema = "Ordering"] public class MyContext:DbContext { public MyContext() : base("name=ConnectionString") { } public DbSet<Student> Students { get; set;...

Am I required to put multiple Entity Framework Models in their own projects in the same solution?

c#,entity-framework-6
I am using Entity Framework 6 in a Windows Form application. The problem is that I have to connect to 4 different databases with almost identical tables. Each year we rollover the databases and allow users in the current year to load 3 previous years of data for some of...

Query in Entity Framework takes longer than direct sql

c#,sql-server,entity-framework-6
The main problem is that when I execute a certain query in SQL Management studio it takes about 2 seconds. When performed through entity framework and I look at it with a profiler the query takes 260 seconds. The result is only 72 rows of 1 integer. This query is...

How to find a List using Find method of entity framework passing Array as parameter? c#,entity-framework,find,entity-framework-6
I would like to know how to find a List<Object> using Find method of Entity Framework passing Array(object[]) as parameter? I want to find all data by Primary Key. I first fill a list with all PK that I will use as reference: List<int> lCodigoServicos = new List<int>(); foreach (ServicosSelecionadosModelView...

WillCascadeOnDelete without base entity knowing of foreign entity

c#,entity-framework,entity-framework-6
I have an entity in my core application: public class Contact : BaseEntity { //Some properties } I then have an entity in a plugin (not part of the main DLL) like so: public class AdditionalContactData { public string SomePropertyThatIsntOnTheMainContact { get; set; } public Contact Contact { get; set;}...

Use multiple conditions in join LINQ. i,e AND

c#,asp.net-mvc,linq,entity-framework-6,repository-pattern
How to use multiple condition in LINQ joins, i.e. in my scenario I need to get all the users from table User where group ID = 4 from table UserInGroup, where UserInGroup is intermediate table between User and Group table as in SQL-T we use join as select * from...

AutoMapper with different instances

c#-4.0,entity-framework-6,automapper
I have two classes public class PatientViewModel { public int Id { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public DateTime DOB { get; set; } } and public class PatientExtended : PatientViewModel...

Why is AutomaticMigrationsDisabledException thrown?

entity-framework,entity-framework-6,ef-migrations
We have An Old Web Project A New Web Project A Class Library containing all Entity Framework code All three projects reference Entity Framework 6.1.3. The Class Library is shared by Old Web Project and New Web Project. Both web projects have a file reference to Class Library. They both...

How to insert rowguid and ModifiedDate in EntityFrameworkDataService

sql-server,entity-framework-6,wcf-data-services
I'm using EntityFrameworkDataService in WCF service and I setup the rowguid and ModifiedData column in DB table. These values are generated by newid() and getdate() in DB. The problem is when I add new object from client application like below: AddressType at = new AddressType(); at.Name = "home"; ccn.AddToAddressTypes(at); ccn.SaveChanges();...

how to use canonical functions in Entity Framework and Mysql

c#,mysql,entity-framework,entity-framework-6
I want to add Timespan to DateTime in EntityFramework with MySql Database. i have tried using DbFunctions.AddMinutes(someminutes) and EntityFunctions.AddMinutes(someminutes) but when i execute i get exception something like FUNCTION projectName.AddMinutes does not exist i have googled but cannot find how to execute canonical function. though there is a list of...