FAQ Database Discussion Community


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

EF code first relation many models to one model

c#,entity-framework,c#-4.0,ef-code-first
I try relashion 2 models to 1 model in Entity framework Code first like that: one model: look at comments public class File { public int ID { get; set; } public int Model_ID { get; set; } // The id of the models public int Type_ID { get; set;...

Insert statement conflicts with FK constraint on ApplicationUsers

sql-server,entity-framework,ef-code-first,asp.net-identity
I've got an Entity as follows: public class EntityX { public int Id { get; set; } ... [ForeignKey("Scheduled By")] public string ScheduledById { get; set; } public virtual ApplicationUser ScheduledBy { get; set; } } When I try to insert a value into the table, I get the following...

Which one should be preferred 1:1,0 or nullable fields on one table on relational database?

entity-framework,database-design,orm,ef-code-first,relational-database
I use Azure Sql and Entity-Framework Code First. I have Transaction Table. There are 4 types which are buy/sell, withdrawal, deposit and fee. For example, I need DepositCode for deposit transactions but this column will be null for others. Also I need ItemPrice and ItemAmount for buy/sell but it will...

MVC project: How to add Seed method

asp.net-mvc,entity-framework,ef-code-first
I am using the standard MVC template which comes with VS 2013. I have Enabled-Migrations. I am also able to add additional tables to ApplicationDbContext. How do I add a Seed method to insert some sample rows to my tables, without disrupting the migration process? Can I insert some rows...

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

When to expose an IEnumerable instead of an ICollection?

asp.net-mvc,entity-framework,ef-code-first,repository-pattern
public class Order { public int Id {get;set;} [DisplayName("User")] public long UserId { get; set; } [ForeignKey("UserId")] public virtual User User { get; set; } public decimal Amount { get; set; } } With IEnumurable public class User { public int Id{get;set;} public virtual IEnumerable<Order> Orders { get; set; }...

EF Relationship Annotation Methods - What are the differences?

entity-framework,ef-code-first
When defining a foreign key relationship using annotations, I see two different ways to accomplish this. Why are there two ways to do this? Is one way more of a standard than the other? Are there any benefits to using one over the other? The one benefit I can think...

EF 6.x Code First: Different SQL Generated for Navigation Property - What am I doing wrong?

entity-framework,ef-code-first,linq-to-entities,poco
I'm a veteran web developer with plenty of T-SQL and schema designing experience, but, fairly new to EF (skipping right to EF 6!). I'm wondering what's wrong with my POCOs that I'm getting different SQL generated for the following two queries. Basically, I have two objects, "Parent" and "ChildThing" with...

How to Keep Entity Framework Code First from using Derived Classes that Aren't Part of the Model

c#,entity-framework,ef-code-first,code-first
Here is a generic example of what I'm doing, what is happening, and what SHOULD be happening: First, I declare my code first model, something like this: Context: namespace Models { public class MyContext : DbContext { public DbSet<ClassA> ClassA { get; set; } public DbSet<ClassB> ClassB { get; set;...

Entity Framework Code First - map same entity twice for different purpose

asp.net-mvc,entity-framework,ef-code-first,code-first
I have two models, One ApplicationUser which holds all users in the system and I have a Quotation model which will hold all Quotations made. now I want to store two mappings to ApplicationUser inside Quotations. So that I can map to created User as well as cancelled User. My...

The entity or complex type 'Ws.Models.XXXX' cannot be constructed in a LINQ to Entities query

c#,linq,asp.net-mvc-4,ef-code-first
I am working along with my MVC4 WEBAPI project. All i am doing is generating a web service using a DTO(samplemodelDTO) which is as follows. namespace Ws.Models { public class samplemodelDTO { [Key] public int id { set; get; } public string Productname { get; set; } public int Productquantity...

How to unit test database access logic?

c#,sql-server,entity-framework,unit-testing,ef-code-first
I have a project based on EF Code First using MSSQL server. In one of my repositories I'm dynamically building a query using PredicateBuilder. To test all possible outcome manually every time something changes in the code, is very time consuming. For that reason, I'd like to automate this by...

Entity Framework - link to all items in a table, then add a new one?

c#,entity-framework,ef-code-first
I have 2 simple C# objects (user and department) as follows (using EF code first): public class User { int UserID {get; set;} string Name {get; set;} List<Department> Departments {get; set;} } public class Department { int DepartmentID {get; set;} string Name {get; set;} List<User> Users {get;set} } I can...

property of the class in null while the database contains it

c#,entity-framework,ef-code-first
I have these two models: public class SystemGroup { public Guid ID { get; set; } public string Name { get; set; } public virtual SystemGroup ParentGroup { get; set; } public virtual ICollection<SystemGroup> SubGroups { get; set; } public virtual ICollection<SystemGroupItem> Items { get; set; } } public class...

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

ModelState.IsValid with DTO and Entity Framework code first

asp.net-mvc,entity-framework,ef-code-first,asp.net-mvc-5,modelstate
ASP.NET 4.5, MVC 5, EF6 code first I'm a newbie and probably asking something long-known but I couldn't find solution on the web, probably because I don't know correct terminology to formulate this question. To simplify things, let's say I have two model classes Teacher and Kid; One kid can...

Does Entity Framework need associations on both sides?

c#,entity-framework,ef-code-first
I have the following model: public class ProductGroup { public int Id {get; set;} public string Name {get; set;} } public class Product { public int Id {get; set;} public int ProductGroupId {get; set;} public string Name {get; set;} public virtual ProductGroup ProductGroup {get; set;} } What is the correct...

How do I create multiple 1:1 foreign key relationships in Entity Framework 6 Code First?

c#,entity-framework,ef-code-first,entity-framework-6,one-to-one
Let's pretend I have three tables, each with a primary key called Id: TableA ------ Id TableB ------ Id TableC ----- Id The intent is for each of these entities to have a one-to-one navigation property with each other so that I may navigate in any direction given any of...

Entity framework creating a non existent column in the query

c#,oracle,entity-framework,ef-code-first
This has been puzzling me for quite some time but I keep getting an invalid identifier error when my entity framework tries to execute an oracle query. The classes in question are the following: public class Projectship : ModelTrackingBase { [Column("PROJECTID")] public long ProjectId { get; set; } [Column("VISITID")] public...

Create a 1 to 1 relation when the Primary Key consist of 2 keys with entity framework

entity-framework,ef-code-first
I have an 1 to 1 relation between 3 tables. The parent table has 2 primary keys (composite keys). Lets name them StudentId1 and StudentId2. What is with the related table where I would put the [Key, ForeignKey("Student")] public int StudentId { get; set; } I do not only have...

The specified type member 'Title' is not supported in LINQ to Entities

c#,linq,entity-framework,ef-code-first
I got an error when using Title property in my Linq to Entity: The specified type member 'Title' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported. my query is: var db = FaraWorkspaceEntity.GetEntity(); var query = from item in db.ProjectManagers where...

Can I call my own methods whilst instantiating objects in Linq to SQL Query?

c#,linq,ef-code-first,entity-framework-6
I have the following query: var userQuizzes = from quiz in Context.Quizzes select new DashboardQuiz { QuizId = quiz.Id, Questions = quiz.Questions QuestionExcerpt = quiz.QuizVersion.Questions.FirstOrDefault().QuestionText // etc... } That's all well and good, but is it possible to call my own methods that perform logic on the data as the...

MVC 5 Unable to determine the principal end of an association on 0..1 to 0..1 relationship

entity-framework,asp.net-mvc-5,ef-code-first
I'm having problems trying to create relationships of 0..1 to 0..1 using code first between AspNetUsers table extending the applicationuser class and MovieModel. The nature of the relationship is that a user can rent one movie or not and a movie can be rented to one renter or not. Each...

How to alter relationship keeping existing data in entity framework code first?

entity-framework,ef-code-first,code-first-migrations
I have two entities public class Account { [Key] public int Id { get; set; public int MemberInfoId { get; set; } public Member MemberInfo { get; set; } //Other Properties } public class Member { [Key] public int Id { get; set; } //Other Properties } With following relationship...

include 3rd level related collection and display in gridview with code-first entity framework

c#,asp.net,entity-framework,gridview,ef-code-first
I have the following template fields in my gridview (ItemType attribute is set properly: ItemType="gEchoLu.Model.DiscussionTimeframe"): <asp:TemplateField HeaderText="Discussion Wall"> <ItemTemplate> <asp:Label runat="server" ID="lbl_Discussion" Text="<%#Item.DiscussionWall.WallTitle %>"></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Course"> <ItemTemplate> <asp:Label runat="server" ID="lbl_Discussion"...

Can one set a breakpoint in EF code first migrations seed method?

c#,asp.net,entity-framework,ef-code-first,code-first-migrations
I am having trouble with something in the Seed method in the Configure.cs for my entity framework 6 code-first migration process. I am running the Update-Database -verbose command in the Package Manager Console, and tried to set breakpoints (in VS studio web express 2013) in the c# code of the...

Deploying to Azure not running EF Code First Migrations

entity-framework,azure,ef-code-first,code-first-migrations,ef-migrations
I am running Entity Framework with Code First Migrations. My new release adds a table, modifies a few tables, and run some scripts. This works perfectly when developing locally using update-database. Upon deployment the new table was not created and I was receiving errors from my client. I attached the...

Entity framework code first using navigation properties a Key

c#,ef-code-first,entity-framework-6
I have the following class in my Entity framework Code First context public class DataBinding { [Key] public DataSource Source { get; set; } [Key] public DataType Type { get; set; } ..... } Both DataSource and DataType are part of the same context, but when i try to create...

Entity Framework Code First Optional Property is mapped as Required

c#,entity-framework,ef-code-first
I have an issue with Code First. I just migrate the project from Model First to Code First and I think that Entity Framework is losing its mind... Here is my class (simplified) : public class MyClass { // Key, other properties... public bool? MyNullBoolean { get; set; } public...

EF Code first migrations not running after deploy to Azure

entity-framework,azure,ef-code-first,code-first-migrations
I have two folders for my migrations (AuthContext and UserProfileContext), each has their own migration and some custom sql to run afterwards for data migrations and whatnot. This works fine when using package manager console. I Restore from production Run Update-Database -ConfigurationTypeName Migrations.Auth.Configuration Run Update-Database -ConfigurationTypeName Migrations.UserProfile.Configuration Then everything is...

Entity Framework Code First Class Library

asp.net-mvc,ef-code-first
Looking for an explanation and education. I created a class library for a code first database and using the app config created a connection string. I then added that to a MVC project. Referencing the class library db context in the MVC project I tried to create a simple record...

Moving Entity framework to another project from MVC causes re-migration

c#,asp.net-mvc,entity-framework,asp.net-mvc-4,ef-code-first
I currently have an asp.net MVC 4 application which contains Entity framework 6 Code First models, DbContext and Migrations. In an attempt to separate this from my web application so I can re-use these database classes in another project I have moved all related Entity Framework classes to their own...

Codefirst and migrations

entity-framework,ef-code-first,code-first-migrations
When an application is Live an iterative approach to database changes is obviously required. In the db first world I would change the object (eg. column added to table) in the databaae project, then deploy (recreate) to my local instance, then replace the old table with the new in my...

Foreign key relationship

asp.net,entity-framework,ef-code-first
I'm trying to setup a foreign key using the following two classes. I want to use pAcqType as an enum and store the names of the types in another table. How should I setup my classes to do this? public class Property { [Key] public int pID { get; set;...

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

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

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

SQL type providers not working correctly for many to many relationship

entity-framework,f#,ef-code-first
I'm trying to use the SqlDataConnection type provider in F# to access a database I've created using entity framework code first model defined in C#. public class Tag { [Required] public int TagId { get; set; } [Required] public string Name { get; set; } public virtual ICollection<Bookmark> TagBMs {...

ED Code First One to Many Relationship Issue - ASP Identity

entity-framework,ef-code-first,one-to-many
I'm configuring a database for ASP Identity and I've hit a snag. I'm looking to create a One to Many relationship between two tables, which are ApplicationUser & OrganisationUnit. An OrganisationUnit can have multiple ApplicationUsers, with an ApplicationUser only belonging to one OrganisationUnit When I add a migration and update...

Entity Framework Code First model from Database design

c#,entity-framework,ef-code-first,entity-framework-6
I'm working on understanding EF (using EF6). I want to go the code first route as that seems to be the trend. What I'm trying to do is figure out how to model what would be multiple join tables in an EF model. My main entities are Staff and School....

Set a constraint for minimum int value

c#,entity-framework,ef-code-first,ef-fluent-api
I am using the Repository pattern. I have a entity called Product and I want to set the minimum value for price to avoid zero prices. Is it possible to create it in a EntitytypeConfiguration class? My product configuration class public class ProductConfiguration : EntityTypeConfiguration<Product> { public PlanProductConfiguration(string schema =...

Multiple cascade paths Entity Framework

entity-framework,ef-code-first,code-first-migrations
My code-first Entity Framework model is as follows: In my database I have customers, purchases and items. A customer may have several purchases Each purchase may consist of several purchased_item. Each purchased_item makes reference to an item. So, when configuring my entities with the FluentAPI I have the following configurations:...

Entity Framework One-Many Relationship on Same Entity

entity-framework,ef-code-first
I need to define Organizational chart schema in Entity Framework. PersonelJob Entity model is: public class PersonelJob : BaseEntity { public Int64 ID { get; set; } public string Name { get; set; } public Int64? ParentId { get; set; } public virtual PersonelJob Parent { get; set; } public...

Using EntityFramework.HierarchyId in CodeFirst approach, The Type hierarchyid is not qualified with a namespace or alias

entity-framework,ef-code-first,entity-framework-6,hierarchy
I'm starting new project and I'd like to use HierarchyID in my DB model and CodeFirst approach. So I added EntityFramework.HierarchyId using nuget. But when I run Update-Database, I receive this exception: Schema specified is not valid. Errors: (0,0) : error 0040: The Type hierarchyid is not qualified with a...

EF6.1 Code First: 1:1 or zero issue with adding records and foreign keys

ef-code-first,entity-framework-6.1
I have two entities, Executive and User. A User can be an Executive but an Executive HAS to be a User. Executive: public class Executive { [Key] public int ExecutiveId { get; set; } // every executive is a user public int UserId { get; set; } [ForeignKey("UserId")] public virtual...

Web ApI Entity Framework (Code First) Value not appearing in database

sql-server,entity-framework,api,rest,ef-code-first
My database will run correctly, and I can input the data manually via SQL Server, however, when I try and pass the value in via my API (testing using Postman), the value won't pass into the database, it appears as "NULL". I have a reports and a bookings tables. This...

How do you perform a rollback when using MigrateDatabaseToLatestVersion

entity-framework,ef-code-first,code-first-migrations,ef-migrations
With EF Migrations you can add migration scaffoldings and then keep running 'Update-Database' to apply changes. And in order to rollback the following works: Update-Database -TargetMigration: <xyzMigration> This is great for updating your dev. DB. However when I automate migrations using MigrateDatabaseToLatestVersion for deploying to other environments like test and...

Entity Framework, Code First, Update independent association (Collection)

c#,entity-framework,collections,ef-code-first
to explain the problem I have a simple model with a class Person: public class Person { public int Id { get; set; } public virtual string Name { get; set; } } and a class School with a collection of Persons: public class School { public int Id {...

Calculated Property in Entity Framework

c#,entity-framework,ef-code-first
I stuck with a problem I have been looking for a solution to, but without much luck. Using Entity Framework Code First, I need the ability to create a calculated property that does not rely on loading all of the objects before calculating. // Psuedo Code for what I need...

Unable to check type of entity of base/inherited classes

c#,entity-framework,ef-code-first
I am having an issue with getting the types of a class based on using GetType() and typeof(), the issue being that it isn't working. I have base class of Content and inherited classes of Podcast and AudioBook. I am using Code First and have a Table per Hierarchy (which...

Adding a migrations gives filename already exists

.net,entity-framework,ef-code-first,code-first,code-first-migrations
I have enabled migrations as such: enable-Migrations -ProjectName ProjectOne -ContextTypeName MyIdentity.Config.MyIdentityContext -MigrationsDirectory Identity\\Migrations I specified my context as it is in a separated namespace, and i specified the directory because i want to have the migrations in a different directory. After enabling the migrations like this, i get the expected...

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

EF code first does not return related relationship for entity

entity-framework,ef-code-first
I'm using Code First and Repository pattern Entity: public class Company : BaseEntity { private ICollection<CompanyRole> _companyRoles; private ICollection<Branch> _branches; public string Name { get; set; } public int CityId { get; set; } public virtual ICollection<CompanyRole> CompanyRoles { get { return _companyRoles ?? (_companyRoles = new List<CompanyRole>()); } protected...

EF Code First 6 and many-to-many with entity mapping

entity-framework,ef-code-first,many-to-many,entity-framework-6
Following the example in this question: How to create a many-to-many mapping in Entity Framework? I would like to have a table mapping where I can add or remove many-to-many relationships without having to go through the Media or Contract entities. Essentially, I would like to have: public class Media...

How to do integration test using Entity Framework Code First V6.1.2

c#,sql-server,entity-framework,ef-code-first,integration-testing
I'm trying to add some integration tests for my database access logic using EF code-first 6.1.2. I'd like to do this on a separate database so that I don't mess up m production database with test data. Also, the test should be repeatable which means the database should be created...

Downloading byte[] file from a SQL Server Compact database

c#,sql,asp.net-mvc,ef-code-first,sql-server-ce
I have an ASP.NET MVC project with Entity Framework. My application accepts a file and saves it as byte[] in my SQL Server Compact database. When I want to view the uploaded file, I want to transfer it to the normal file format. How is that possible? This is my...

Need to map an EF entity property to a column using another property's name

ef-code-first,entity-framework-6,data-annotations
I took out logic from the accessors to make the code cleaner. I have a table with a column named "Answer" and I have existing code that uses the entity property "Answer". I need to minimize changes to the db and code base. The requirement is that Answer is to...

Update existing database with Entity Framework Code First in MVC

sql-server,asp.net-mvc,entity-framework,ef-code-first,updatemodel
In my MVC application I used Entity Framework 6 and created database with code first approach. After a certain time, I updated one of the entity classes by adding new column and removing some columns. For reflecting these changes to the database I followed the steps below: Deleted the migrations...

Code first refuses to cascade delete an entity

c#,entity-framework,ef-code-first
I have a Parent entity with a 0-to-Many relationship to a Child entity. When I delete a parent I want it to automatically cascade delete all the attached children. Attempting to do so gives the following exception... The operation failed: The relationship could not be changed because one or more...

why we need to use AsEnumerable() method?

c#,linq,lambda,ef-code-first
This code causes a NotSupportedException. var detailList = context.Details.Where(x => x.GetType().GetProperty("Code").GetValue(x,null).ToString() == "00101").ToList(); But this code works. var detailList = context.Details.AsEnumerable().Where(x => x.GetType().GetProperty("Code").GetValue(x,null).ToString() == "00101").ToList(); MSDN says: - AsEnumerable() Returns the input typed as IEnumerable - DbSet Is an IEnumerable So why we need to use AsEnumerable() method?...

EF6 Code First throwing NullReferenceException when no PRIMARY KEY exists

ef-code-first,entity-framework-6
This is a bit of a strange one. I do not have administrative access on the database and am working with a table that is properly constrained, but has no primary key defined. The schema is as follows: CREATE TABLE Foo ( KeyColumn VARCHAR(100) NOT NULL UNIQUE, BitValue BIT NOT...

(Keep orphans alive) How to map child entity to set parentID property to null on father delete

c#,entity-framework,ef-code-first
In EF Code First: how do we map the child entity to set parentID property to null on father delete? (Keep orphans alive) Example: class FullGroup - ID, Name, IEnumerable<Machine>() Machines, etc.... class Machine - ID, Name, virtual FullGroup? (asnullable), int? FullGroupId, etc..... this.HasOptional(t => t.FullGroup) .WithMany(t => t.Machines) .HasForeignKey(t...

How can I solve this “System.Data.Entity.DynamicProxies” error

c#,asp.net,linq,entity-framework,ef-code-first
I am new to Linq and EF Code First and came across an issue that I just can't figure out. I am developing a proof of concept examination program using ASP.Net Web Forms, EF Code First and Linq. The ideas is that I generate the page's server controls dynamically based...

EF Code First and indicating a simple foreign key

entity-framework,ef-code-first,foreign-keys,entity-framework-6
Let's say I have an entity EntityA with two unique columns, Key1 and Key2. At the moment only Key1 is the PK. Now I want another entity named EntityB, to have a FK from EntityB.AKey2 to EntityA.Key2. I don't need a navigation property from one to the other, just to...

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

ef-code-first,asp.net-mvc-5,seeding
I am working with Entity Framework Code First and MVC 5. When I created my application with Individual User Accounts Authentication I was given an Account controller and along with it all the required classes and code that is needed to get the Indiv User Accounts authentication to work. Among...

Default values not supported in SQL CE 4 and EF 6 code-first

c#,sql-server,entity-framework,ef-code-first,sql-server-ce
I have the following code-first model: public class TestContext : DbContext { public TestContext() : base("Data Source=Test.db") { } public DbSet<Item> Items { get { return this.Set<Item>(); } } } public class Item { public Int32 Id { get; set; } public virtual ICollection<SubItem1> SubItems1 { get; set; } public...

Entity Framework code-first: querying a view with no primary key

sql,oracle,entity-framework,view,ef-code-first
Our customer has given the access to views in which there is no primary key is defined. I know Entity Framework needs a primary key for table to identify. But for views not having primary key is it still possible to query. I try to find but always Entity Framework...

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

The property 'Id' is part of the object's key information and cannot be modified. On INSERT

c#,entity-framework,ef-code-first
I know there are many other questions like mine but none of the answers have helped me so far. Im creating a mvc website using Code First. So far so good. The database have been created and now I want to insert some data using the code. But keep getting...

How to define a table that its primary key is constructed from 2 foreign keys with EF code-first

c#,entity-framework,entity-framework-4,ef-code-first,code-first-migrations
I am using models to define my tables using EF code-first. I have and Item model and an Order model. Item: public class Item { public int ItemID { get; set; } [Required] public int Price { get; set; } [Required] public int AmountLeft { get; set; } [Required] public...

How to configure TPH using Fluent API in EF code-first?

c#,entity-framework,ef-code-first
I have 2 models, where the second model inherits from the first one and has additional properties: public class Item { public int Id { get; set; } public string Name { get; set; } } public class ItemMap : EntityTypeConfiguration<Item> { public ItemMap() { this.ToTable("items"); this.Map(m => m.Requires("type") .HasValue("Type1")...

Entity Framework and property containers

vb.net,entity-framework,ef-code-first
I'm working on an EF set of data classes and one of the classes is rather large on properties. However, a number of the properties can be grouped into sub categories and I'd like to do that to help with clarity. Its also being developed as Code First. e.g. For...

how to use where with list of string

c#,entity-framework,ef-code-first
I have List Of string Like as "one" , "two" , "three" ,... I want Search From DataBase and select All Items Where have At least On of them , I wnat do this by Entity framwork , To do this I use : if (SearchVM.Tags.Count > 0) //SourceList= SourceList.Where(x=>x.Tags.Where(...));...

Creating an entity with a reference to an other entity in azure mobile service

c#,entity-framework,azure,ef-code-first,azure-mobile-services
I've created a azure mobile service which basically consist of 2 Entities and 2 TableControllers. Those both entities have a 1:1 relation. public class Entity1 : EntityData { public int Value { get; set; } public DateTime Date { get; set; } public string Name { get; set; } public...

Circular foreign key code first

asp.net,entity-framework,ef-code-first,asp.net-identity
I am creating a system that requires a user to approve actions in an application. One of the actions is adding a user the work flow is as follows. An existing user adds a new user. This action creates a row in the user table and a row in the...

Entityframe work database

entity-framework,ef-code-first,code-first
I'm using this EF framework trying to learn it with the code first approach. I've following a couple articles. My question is where is my data base I've looked at this article HERE but still can not fid the db. I'm using VS 2012 and didnt specify the connection string...

Adding column in Entity Framework 6.1 - Many-To-Many - Code First

c#,entity-framework,ef-code-first,many-to-many,code-first
Just as an example I'm using the code from this article on codeproject: http://www.codeproject.com/Articles/234606/Creating-a-Many-To-Many-Mapping-Using-Code-First Im trying to do something similar in my code but I also want a quantity property, so: One course can have many persons One Person can have many courses Each person can choose a quantity of...

Unit of Work Pattern And Updating Entity Collection Properties

c#,ef-code-first,entity-framework-6,unit-of-work
I'm using generic repository pattern with unit of work implementation for my project. Recently I've come to an issue which I could not solve. When I try to update an entity's collection property (i.e: Add a new associated entity) and call update on my UoW (to delegate it to repository...

LINQ Include condition not applying

c#,linq,ef-code-first
I have the following two entities: public class Artist { public int Id { get; set; } public string FName { get; set; } public string LName { get; set; } public string UrlFriendly { get; set; } public string ImgURL { get; set; } public bool Verified { get;...

Entity framework code first reference many models to one model

entity-framework,ef-code-first
How to reference many models(Lesson, Set) to one model (File) public class File { public int ID { get; set; } public int Path { get; set; } } public class Lesson { public int ID { get; set; } public virtual File File { get; set; } } public...

Foreign key not uppdated (configured with required principal-dependent)

c#,entity-framework,ef-code-first
Fluent API config: internal class UserMap : EntityTypeConfiguration<User> { public UserMap() { Property(x => x.CSL).IsRequired(); //relational properties HasRequired(x => x.UserType).WithMany(x => x.Users).HasForeignKey(x => x.UserType_ID).WillCascadeOnDelete(true); HasRequired(x => x.TimelineVolumetry).WithRequiredPrincipal(x => x.User).WillCascadeOnDelete(true); } } internal class TimelineVolumetryMap : EntityTypeConfiguration<TimelineVolumetry> { public TimelineVolumetryMap() { Property(x =>...

Unable to determine the principal end of an association between the types [duplicate]

c#,entity-framework,ef-code-first,one-to-one,ado.net-entity-data-model
This question already has an answer here: What does principal end of an association means in 1:1 relationship in Entity framework 4 answers Here is the situation. There are two type of ElectricConsumer ie CommercialConsumers & DomesticConsumers(Quaters) and one Quater is allocated to one Employee. Below is my code...

Entity framework code first many to many with extra key

c#,entity-framework,ef-code-first
I'm trying to create a linked table that will allow me to have a many to many relationship between my product and accessory tables. My classes are like this: public class Product { public int Id {get; set;} public string Name {get; set;} public virtual ICollection<Accessory> Accessories {get; set} }...

Code First Migration tries to re-create enitre db instead of updating changes

asp.net-mvc,ef-code-first,code-first-migrations
Im trying nto enable Migration with code first but im having some issues. Im working on a mvc5 website and I have a dll with the datalayer, dll with the domain classes and then the website itself. I have already run the website and all the tables have been created....

How to change default naming convention in Entity Framework CodeFirst?

c#,entity-framework,ef-code-first
In my DB, the foreign keys following the following convention: category_id, product_id, etc... How can I change EF's default naming convention and would I need to do it for every table?...

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

Entity Framework 6 composite key (DateTime + foreign key)

database,entity-framework,ef-code-first
I have to store the following entities in a database: devices measuring points measured values where each device has one or more measuring points. The measured values table will store values for each measuring point every 10 minutes. This table will have millions of records after a few years and...

“The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical” issue in entity framework

c#,entity-framework,ef-code-first
I'm using .NET framework 4.0 with Entity Framework v6 code-first. I am creating 3 tables ("Indicadores", "Campos" and "Codigos") which use composite primary keys, but I am receiving an error when generating the model: One or more validation errors were detected during model generation: Codigos_Campos_Target_Codigos_Campos_Source: : The number of properties...

Entity Framework : Create a model from Dictionary to be mapped to a database table

sql-server,entity-framework,ef-code-first
Earlier I had a table named ApplicationConfiguration which simply had [Key],[Value] columns to store some config data. This was queried straight away using SQL queries. Now I intend to make use of Entity Framework (EF) Code First approach to query this table. The specialty of this table is that the...

One to zero or one relationship entity framework

c#,entity-framework,ef-code-first,ef-fluent-api
I am trying to enforce a one to (zero or one) table relationship using code first/fluent api and the intended table is as below. Student may only have a contact (StudentContact) or not But Every contact (StudentContact) must have a Student StudentID StudentName 1 StudentA 2 StudentB StudentContactID StudentContact StudentID...

Getting ObjectContext error even after calling ToList

entity-framework,ef-code-first
When calling the method directly below I get a ObjectDisposedException when calling Mapper.Map with the retrieved list. System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. public IEnumerable<Models.Provider> Get(string owner) { List<Data.Models.Provider> providers; using (var db = new Data.ProviderDirectoryContext()) {...

Using custom methods in linq to entities

c#,entity-framework,ef-code-first,linq-to-entities
I have a Person table in my database that has NationalId field. Is there any way to load all Persons with even NationalId, using Ef code first and Linq to entities, without loading all Persons to memory? Somethings like: public bool IsEven(int number) { return number % 2 == 0;...

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

Checkbox carries the value but not the title

asp.net-mvc,entity-framework,razor,ef-code-first
I have a many to many relationship which I have implemented and works perfectly, now I want to have a set of checkboxes on the "insert" page of one of the entities that can insert data in the intermediary table. I have a ViewModel, which contains an array of the...

What is modelBuilder.entity(Of x)

c#,vb.net,ef-code-first,entity-framework-6
I have a context class for an EF 6 project that has the following modelBuilder properties for each column in each table: Protected Overrides Sub OnModelCreating(ByVal modelBuilder As DbModelBuilder) modelBuilder.Entity(Of Product)() _ .Property(Function(e) e.Name) _ .IsUnicode(False) modelBuilder.Entity(Of Product)() _ .Property(Function(e) e.Description) _ .IsUnicode(False) End Sub What is this for? In...

C# - EF 6 Relationships Fluent API (1:1..0)

c#,entity-framework,ef-code-first,foreign-keys,ef-fluent-api
I'm having some trouble finding out the correct way to map my Client/Person classes in the EF 6.1.3. public class Client { public int ClientId { get; set; } public int PersonId { get; set; } // FK // Navigation Properties public virtual Person Person { get; set; } }...

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

How to seed identity seed value in entity framework code first for several tables

c#,entity-framework,ef-code-first
I have seen this and this . I simply wish to seed the start value for ID columns for my code first ( EF6.1) tables. Now I can do this public class CustomInitializer : CreateDatabaseIfNotExists<FormsDbContext> { protected override void Seed(FormsDbContext context) { context.Database.ExecuteSqlCommand("DBCC CHECKIDENT ('MyTable', RESEED, 1000)"); } } But...

Run Code First Migration Seed Method without a migration

entity-framework,ef-code-first
How do you run a code first entity framework migration without changing anything in the datamodel which would cause a migration to be created? I just want to run the seed method again because I added things to it.