FAQ Database Discussion Community


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

Why does .Where() with a Func parameter executes the query?

c#,oracle,linq,entity-framework
Here's how my DataAccessLayer works : public Foo GetFooBy(Func<Foo, bool> filter) { var query = from item in this.DataService.FooSet select item; var where = query.Where(filter); var first = where.First(); return first; } I assumed the query would be run when First() is called but it's actually executed by the Where()....

LINQ to SQL: How to create something like conditional include?

.net,linq,entity-framework,include,condition
I'd like to create a query contains User whose entities has Event with type == 1. I would also like the Event entries loaded into EventsCollection. My code would be something like .Include(u => u.EventsCollection), but this only loads all Event entries - I want to load only with type...

Entity Framework query return my primary key plus $id

c#,json,asp.net-mvc,entity-framework,linq-to-sql
This is my model class public partial class TLog { [Key] public int idLog { get; set; } public string description { get; set; } public System.DateTime insertDate { get; set; } } And this is my query method: public static List<TLog> GetAllLogs() { var query = from log in...

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

Linq where on include

c#,linq,entity-framework
I'm stuck with this linq query. I've this tables. ID A B C D 1 some data 2 some other data Then, For every record on that table I may have none or many rows ID TableA_ID R 1 1 1 2 1 2 3 1 5 4 2 2...

How to use OR in join while using Entity Framework

entity-framework,sql-server-2008
Can any one convert following SQL statement to Entity Framework C# or VB.net for me? SQL statement: select t1.*, t2.* from tblWISTransacs t1 inner join tblWCBTransacs t2 on t1.TicketNo = t2.TicketNo or t1.TicketNo = t2.customernumber ...

Why does adding a parameterless constructor to my entity model class work here? What are the implications?

c#,entity-framework,generics,constructor
So I have this office entity class: [Table("office_entity")] public class EFOffice : EFBusinessEntity { [Column("address")] [StringLength(250)] public string Address { get; set; } [Column("business_name")] [StringLength(150)] public string BusinessName { get; set; } public virtual ICollection<EFEmployee> Employees { get; set; } public EFOffice(Guid id, Guid tenantId, string address, string businessName) {...

ApplicationUser ICollection member not being saved in DB

c#,.net,entity-framework,asp.net-mvc-4,asp.net-mvc-5
I've added some properties to ApplicationUser, and two of them are ICollection's. When I use Update-Database it doesn't generate columns for these two members. So, what am I missing here? I imagine it's very basic. I'm used to working with Hibernate in Java, where it generates a new table for...

Entity Framework Invalid Column (Column Does Not Exist in Database or Code)

c#,.net,entity-framework
So I have seen a lot of questions like mine. But none of the answers are working. Anytime I try to update the entity I get an Invalid Column exception: [SqlException (0x80131904): Invalid column name 'ssma$rowid'. Invalid column name 'ssma$rowid'.] Where is this coming from? I have regenerated/rebuilt/cleaned/dropped table and...

Viewmodel binding for Edit View

c#,entity-framework,mvvm
Having some trouble with the "GET" part of the Edit View, and can't really find anything online. So far, this is my POST section: [HttpPost] public ActionResult Edit(ContactsEditViewModel viewModel) { if (ModelState.IsValid) { var Contacts = TheContactContext.tblContacts.Find(viewModel.ID); Contacts.Company = viewModel.Company; Contacts.Contact = viewModel.Contact; Contacts.Contact2 = viewModel.Contact2; Contacts.Email1 = viewModel.Email1; Contacts.Email2...

Entity Framework - How to get Standard Deviation using GroupBy?

.net,entity-framework,aggregation,standard-deviation
I'm using entity framework 5, code first fluent API. I've built a simple query with a GroupBy for aggregation: var query = context.Table1 .GroupBy(g => new { Prop1= g.Prop1, Prop2 = g.Prop2 }) .Select(s => new { Prop1= s.Key.Prop1, Prop2= s.Key.Prop2, Avg = s.Average(m => m.Minutes), Min = s.Min(m =>...

Changing the Database Schema on a linking table (many-to-many) in EF

c#,entity-framework,ef-fluent-api
I am creating a many to many relationships with my EF Models. The linking table is being created which is fine, but it keeps putting it on the DBO Schema which I do not want. Yes, I could just modify the migration script after its generated but that should be...

Using SqlQuery in Entity Framework

sql-server,entity-framework
Is this really true that order of sql parameters in sql stored procedure must match the order of sql parameters used in SqlSquery: var Parameter = new List<SqlParameter>(); Parameter.Add(new SqlParameter("@ParamOne", 1)); Parameter.Add(new SqlParameter("@ParamTwo", 2)); Parameter.Add(new SqlParameter("@ParamThree", 3)); context.Database.SqlQuery<myEntityType>("exec sp_Stored_Procedure @ParamOne, @ParamTwo, @ParamThree", Parameter.ToArray()).ToList<myEntityType>(); And in case sql developer decides to...

Entity Framework: how to annotate two one-to-one relationships to same table

entity-framework
In a punch clock application, a given day has two foreign keys into the Punches table: PunchId_In and PunchId_Out. How can you annotate this relationship so Entity Framework creates it as intended? Note: One or both of these foreign keys may be undefined (null). public class Day { public int...

Putting serialized Entity Framework objects back in Database

c#,sql-server,entity-framework
I am new to EF and am having trouble deserializing an object and then putting it back in the SQL Server Express (2014) DB . For this demo, I have just two tables, "Patient" and "Session". A Patient has 0 or more Sessions. The idea is to allow the user...

How to display WCF HTTP codes in service response

c#,json,entity-framework,wcf,rest
I'm working through a web service using WCF and Entity Framework and I would like to know how to view or return HTTP status codes to the calling clients. The code I have is as follows: IUserService.cs [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = "/GetUsers")]...

ASP.NET EF6 - 2 Tables & 1 Link Table

c#,sql-server,asp.net-mvc,entity-framework
I am not the most fluent with ASP.NET/EF, so I am having a bit of a hard time trying to find the best way to accomplish what I need to get done. I'm trying to create a CRUD with an already existing database. Instead of the Employees table having specific...

How do I mock multiple levels of DbSet.Include lambdas?

entity-framework,unit-testing,lambda,moq
I'm using Moq to write unit tests that use Entity Framework 6 DbSet and DbContext objects. I have a service method with a cascading/multi-level Include and I can't figure out how to set it up for testing. The service method looks something like this: return DataContext.Cars .Include(p => p.Model) .Include(p...

How can I verify that RemoveRange has been called on a mock DbContext?

c#,entity-framework,unit-testing,moq
I am using Moq to test code that calls RemoveRange on a DbSet<T>. I have mocked the context object and DbSet, but when I attempt to Verify that RemoveRange was called, I get "Expected invocation on the mock once, but was 0 times." The method I'm testing has this code:...

Avoid EF update the null image to database in .Net MVC

asp.net-mvc,entity-framework,null,edit,httppostedfilebase
In my SachController, there is an Edit method like below. In the view, there are several textbox and one file-input for upload image object. Sometime, user doesn't want to change the image and they just don't select a new image. And the image (HttpPostedFileBase) is null. How can I avoid...

LINQ search query doesn't work

c#,asp.net,asp.net-mvc,linq,entity-framework
I'm trying to write a search query in LINQ. Below is the where condition. where (!string.IsNullOrEmpty(nameWithInitials) && tb.NameWithInitials.Contains(nameWithInitials)) && (!string.IsNullOrEmpty(studentRegNo) && tbSR.StudentRegistrationNo.Contains(studentRegNo)) && (!string.IsNullOrEmpty(NIC) && tb.NIC.Contains(NIC)) && (!string.IsNullOrEmpty(fullName) && tbi.Name.Contains(fullName)) It doesn't return any values if I pass a single parameter. For example if I pass 'Chamara' as fullname...

failed to set database initializer

c#,asp.net,asp.net-mvc,entity-framework
I'm learning ASP.NET MVC5 to make a website. I created several classes in the model folder and used "scaffolding feature" in Entity Framework to create CRUD pages. Everything is fine in the Home page. But when I clicked the "Employee" link in the navigation bar, there was an error in...

Get a single text value using linq

c#,asp.net-mvc,linq,entity-framework,asp.net-mvc-3
I am using this line to return a value, but instead its getting a True var valor = valoresCampoAdicionalesEmpresa.Select(p => p.Key == propiedad.Nombre).First(); This the view data passes from the controller var valoresCampoAdicionalesEmpresa = (Dictionary)ViewData["ValoresCampoAdicionalesEmpresa"]; public ActionResult Edit(int? id) { var listFields = from b in db.Propiedades where b.Entidad.Nombre ==...

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

ModelState.isValid - false

c#,asp.net,asp.net-mvc,entity-framework
I would like to get parameter from dropdownList on html page and send it to my controller, create new Model object, and insert it into database. it's my controller (two methods to create My_Model): public ActionResult Create() { IEnumerable<MusicStyle> musicStyleList = db.MusicStyles.ToList(); ViewData["musicStyles"] = new SelectList(musicStyleList); return View(); } //...

How to set default length on all fields in entity framework fluent api?

c#,.net,entity-framework,ef-fluent-api
Is it possible to set default length of all string fields (unless I say otherwise)? At the moment it really bugs me to go and add something like modelBuilder.Entity<Game>().Property(x => x.YardLine).HasMaxLength(256); to each and every string field, just to avoid having nvarchar(max) on all my strings columns in the database....

EF Migrations - should an initial migration be automatically generated?

entity-framework,code-first-migrations
I have a project that uses EF code-first. It has automatically generated a DB from the model. Now, I want to enable EF migrations. The 'Getting Started' docs on EF Migrations suggest that in this scenario (DB already exists), two things should happen when calling Enable-Migrations: the project gets updated...

How does the Take() method work in LINQ

c#,.net,linq,entity-framework
I have a question regarding LINQ's Take() Method. I have a somewhat large table I'm querying in my web app, and I only want to return say N number of rows from the table. I've read through the MSDN documentation, but I can't see where it states if Take() first...

Is there a difference between using for-each and Contains in joining on a qeury

c#,linq,entity-framework,join
Let's say I am doing a JOIN like this below: var query1 = (from ga in this.Context.GroupAddress join gpa in this.Context.GroupsProvidersAddresses on ga.GroupAddress_K equals gpa.GroupAddress_K where this.TerminatedGroupAddressesKeys.Contains(ga.GroupAddress_K) select gpa.ProviderAddress_K).ToList(); where TerminatedGroupAddressesKeys is a collection of strings that I have and I am using .Contains Is that different from doing a...

How to override Azure Sql connection in Azure portal

entity-framework,azure,sql-azure
I tried to override connectionstring in Azure portal with this connection : Server=tcp:server.database.windows.net,1433;Database=mydatabase;User ID=username@server;Password=xxxxxx;Trusted_Connection=False;Encrypt=True;Connection Timeout=30; It gives me an error Keyword not supported: 'server' and when I tried it as: metadata=res://*/DataAccess.MyDataBase.csdl|res://*/DataAccess.MyDataBase.ssdl|res://*/DataAccess.MyDataBase.msl;provider=System.Data.SqlClient;provider connection string=&quot;data...

Should i validate if related entity exists before insert?

c#,entity-framework,domain-driven-design
class Customer { public int Id { get; set; } } class Sale { public int Id { get; set; } public int CustomerId { get; set; } } class SaleService { public void NewSale(Sale sale) { //Should i validate if Customer exists by sale.CustomerId before call save? saleRepository.InsertOrUpdate(sale); }...

deleting and then inserting values using Entity framework

entity-framework,unit-of-work
My requirement is that i require to delete some rows from table and then insert some in the same table. I am using Unit of work and so both deletion and insertion are part of same transaction. But when i am trying to save the data, entity framework is duplicate...

C# entity framework MVC second run error

entity-framework,asp.net-mvc-4,localdb
I am creating db and initializing data with code below, if DB doesnt exist, it creates db and populate it, when I run application second time I get error Cannot drop database "aspnet-app" because it is currently in use. Application_start, with initializations protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes);...

Query to entity framework 7 using linq and related entities

c#,mysql,linq,entity-framework
I have this query witch is working fine : List<IGrouping<Country, VisitedCity>> tempQuery = null; using (var db = new MyDataContext()) { tempQuery = db.VisitedCities.Include(c => c.PersonWhoVisited).Include(c => c.PersonWhoVisitedNationality).Include(c => c.City) .GroupBy(c => c.PersonWhoVisitedNationality) .ToList(); } var dataInput = tempQuery .OrderBy(c => c.Key.Name) .Select(cp => new { CountryName = cp.Key.Name, VisitationsByCity...

Conditionally refine database query based on non null filters

asp.net-mvc,entity-framework
I have 15 columns in my view page e.g. Reference name, shape, color, weight, price etc I am getting all these to data to refine the database, if user does not select shape then it not use shape to refine, whatever user selects for refinement only those item should be...

Is querying directly against tables somehow okay now?

sql,entity-framework
In the past, any database administrator worth his salt would have told you never to query against a table directly. In fact, they would have prevented it by putting all tables in one schema & cutting-off direct access to that schema...thereby forcing you to query or CRUD from views &...

Exclude underlying objects when storing data using EF6

asp.net,entity-framework,asp.net-web-api
I have a class Ticket which has some properties. Three of these (View, Task and Key) properties are navigation properties. Those properties already exist in database even before a ticket has been stored. In my application I load those properties from the database first and then create a Ticket object....

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 to CSV float values

c#,entity-framework,csv
I'm trying to write an object to csv, the thing is that my objects have float valure for exemple (14,9) i want to change them to (14.9) so it won't cause any problem with the csv format string csv = ""; using (var ctx = new NBAEntities2()) { var studentList...

Foreign key not updating in entity frame work

c#,.net,entity-framework,foreign-keys
I have a class like public class Document { [Key] public int Id { get; set; } public User ModifiedBy { get; set; } public DateTime ModifiedDate { get; set; } } Here “User” is a class with some properties (all are primitive types ) Here is my mapping of...

Methods defined in an interface can no be used from another class

c#,entity-framework,interface
I am using Entity Framework 4.1 and code-first approach. I have the following intefaces namespace BackupCore.Contracts { public interface IEntity { DbSet getDbSet(BackupCoreContainer context); bool isNew() ; } } namespace BackupCore { interface IDao<IEntity> { IEntity Save(IEntity ent); IQueryable<IEntity> GetAll(); bool Delete(IEntity ent, out String errMsg); void SaveChanges(); } }...

How to use Join and Where to return an IList?

c#,linq,entity-framework
How can I achieve a join and a where in C# MVC using something like Linq or EF Join? This is the equivalent SQL I am trying to achieve. select * from promotion P JOIN PromotionsClaimed PC on PC.PromotionId = P.objectid where PC.userId = @USERID This method should return a...

How to create an input (editorfor) for a field not in the model

c#,asp.net-mvc,entity-framework,asp.net-mvc-3,razor
I have the following on my EDIT view @model Inspinia_MVC5.Areas.GlobalAdmin.Models.Empresa @{ ViewBag.Title = "Edit"; Layout = "~/Areas/GlobalAdmin/Views/Shared/_LayoutGlobalAdmin.cshtml"; var camposAdicionalesEmpresa = (List<Inspinia_MVC5.Areas.GlobalAdmin.Models.Propiedad>)ViewData["CamposAdicionalesEmpresa"]; var valoresCampoAdicionalesEmpresa = (Dictionary<string, string>)ViewData["ValoresCampoAdicionalesEmpresa"]; } and my controller is like this: public ActionResult Edit(int? id) { var listFields = from b in...

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

Deleting a row using entity framework

c#,entity-framework
I'm trying to delete a row from a table in my database but I keep getting a null reference exception. I know that the code I wrote isn't grabbing the ID number from the ComboBox but I don't know how to fix it. Here's the code I have: private void...

Updating entity framework model using Linq

c#,sql,linq,entity-framework
I have a problem with updating data in an entity framework model. I have a few tables in the model (Users, UserActivity and Orders). I have added associations between the tables, one between Users and UserActivity and one between Users and Orders. The associations are through the column UserID. These...

Entity Framework 6 and migration when I don't have a default Database

c#,database,entity-framework,code-first-migrations
I have a solution where I do not have one default database. I have a master Database that are returning a connection string for the customer that is requesting data, and each customer has their own database. I am using migration (and has AutomaticMigrationsEnabled set to false) and code first....

EF Intersect Syntax

c#,entity-framework,linq-to-entities
A UI allows users to select one or many tags. I would like to select all Nodes that have ALL that tags the user entered associated, not just a single tag. public JsonResult SearchNodesByTags(string[] tags) { var dbTags = _DbContext.Tags.Where(t => tags.Contains(t.DisplayName)).ToList(); var nodes = _DbContext.Nodes.Where(n => n.Tags.Intersect(dbTags).Any()); // Error...

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 specify the range of rows my LINQ query should retrieve

c#,asp.net-mvc,linq,entity-framework
I have the following LINQ query: List<Person> people = db.People.Take(pageSize) .OrderByDescending(t => t.Id) .ToList(); The goal is to specify range of rows which should be get. I want to do it with where statement. The question is how is it possible to put specific indexes of rows into the where...

Managing per form ObjectContext lifetime

c#,winforms,entity-framework,orm
For ORMs like EF and NHibernate, multiple places suggest using "context per method" (or per request, per transaction) for web apps and services and using "context per form" for thick clients like WinForms and WPF. In C#, resource disposal with context per method is clean and clear with a using...

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

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

Iterating over two lists in c#

c#,asp.net-mvc,linq,entity-framework
So i have a function that gets a list of students from a web service and also query the localdb for all the students in there. the data is placed in two different list. So i want to check to see if a new student already exists in the localdb...

How to map between two entities before paging

c#,asp.net-mvc,entity-framework
Consider the code below: public ActionResult Index(int? page) { List<ProviderViewModel> viewModel = new List<ProviderViewModel>(); List<Provider> businessModel = db.Providers .OrderBy(t => t.Name); foreach (Provider provider in businessModel) { viewModel.Add(new ProviderViewModel(provider)); } int pageSize = 9; int pageNumber = (page ?? 1); return View(viewModel.ToPagedList(pageNumber, pageSize)); } I'm using PagedList.MVC (from NuGet) and...

startIndex cannot be larger than length of string

c#,entity-framework,asp.net-mvc-4
I try to check if a foldername doesnt has a extensie. Because I want to change the name of the folder. But you can also change the name of a file. But I get this error: "startIndex cannot be larger than length of string.\r\nParameter name: startIndex"} By this line: string...

How to avoid async/await deadlock when blocking is required

entity-framework
I have the following issue that the SingleOrDefaultAsync from EF do not complete. I added two extra calls evaluating to a and b which both returns the correct value. But the test line is never completing and the method just waits for ever. Anyone experienced something similar or have some...

How return ID or all from another class with Entity Framework?

c#,asp.net,entity-framework,class
I learning Entity Framework, so don't blame me if this is easy for you I have class HomeNumber.cs [ScaffoldColumn(false)] [Key] public int HomeNumberId { get; set; } //[ForeignKey("HomeNumberId")] //public virtual HomeNumber HomeNumbers { get; set; } [Required(ErrorMessage = "Polje kućni broj je obavezno!")] public string HomeNumberName { get; set; }...

When are Entity instances automatically attached to a context?

c#,entity-framework
I've read a few questions and texts on attachment but they seem to skip some detail on how it works. For example, I don't know why the following happens: MyContext c = new MyContext(); MyEntity e = new MyEntity(); /* some local edits in e */ c.MyEntity.Add(e); // Works fine...

Passing conditional parameters to Database.SqlQuery

c#,sql,linq,entity-framework
I have been doing the following to pass parameters with my sql query: var retval = context.MyObject.SqlQuery(sql.ToString(), new SqlParameter("@ProductId", productId), new SqlParameter("@CustomerId", customerId)).ToList(); I ran into a scenario where @CustomerId will not always be used in my sql string. Meaning I used an if statement to either add (Where p.CustomerId...

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

SQLite.net Extensions loads the same entity multiple times rather than returning the same reference

entity-framework,entity-framework-7,sqlite-net-extensions
I'm using the PCL version of SQLite.Net Extensions in a Windows 10 universal app. This is my first time using it. It generally seems to be working, but it appears to be loading an entity multiple times rather than reusing a reference to the same object. According to the SQLite.Net...

entity framework validation context - null exception in null test

c#,entity-framework
I am working on PC configurator application and I have a problem with validating. Point of app is to check if socket on motherboard is the same as socket of CPU etc. I made code first database using scaffolding in Visual Studio 2013. public class Configuration : IValidatableObject { [Key]...

Updating a record using a class object with Entity Framework in C#

c#,entity-framework
I have an entity class which includes many fields. To make it simple, let's assume the class is defined as following: public partial class Branches { public int num { get; set; } public string name { get; set; } public string street { get; set; } public string city...

how to update multiple data in entityframework through async web api

entity-framework,asp.net-web-api,async-await,web-api,asp.net-web-api2
I am using web api 2, and entity framework 6. I have created an async web api, which updates all the records at once. I am also using Autofac for dependency injection. My service interface is as follows : Task<Approval> TakeAction(int id, bool isApprove) void TakeAction(bool isApprove) These are my...

How to solve error in Configuration.cs in code first migration

c#,asp.net-mvc,entity-framework
I was setting up code first migration for model changes from Package Manager Console which creates seedmethod in Configuration.cs. i placed my code in Seed method and it shows error at context.Movies.AddorUpdate(----- it says : The type arguments for method 'System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate(System.Data.Entity.IDbSet, params TEntity[])' cannot be inferred from the usage. Try...

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

Sort a LINQ with another LINQ in MVC

sql-server,linq,entity-framework,controller
Using SQL Server Management Using MVC VS 2013 for Web Being in a Controller Here materialnumb it's a LINQ query that always return only one value. Being the following... var materialnumb = (from r in db.MaterialNumber where r.MaterialNumber == 80254842 select r.MaterialNumber); I have another LINQ query from a...

How to assign list to generic list

c#,entity-framework
How can I assign return result from table to generic list This is a WCF service method. public List<T> GetApprovedStateList(DateTime effectiveDate) { List<T> stateList = null; using ( var db = new Context()) { stateList = (from a in db.StateProductList join b in db.States on a.stateID equals b.stateID where a.effectiveDate...

Entity Framework throws Invalid object name

c#,sql-server,entity-framework,ado.net,asp.net-web-api2
I have a DB in SQL Server with several tables. I have created a Class Library project in VS2013. Created a DBContext, added the database as a ADO.NET file and created a repository for running the queries. I have created a Web API2 empty project with a controller for creating...

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

Enforce ordering of OData items even when $top is used

linq,entity-framework,asp.net-web-api,odata,iqueryable
I have a DbSet<Items> collection. The primary key is a Guid. I don't want to order by this primary key. I want to order by an editable decimal property named "Order". The code I have is very simple, and it works great until the user puts a "$top" parameter into...

Unable to find the auto created Database

c#,asp.net,asp.net-mvc,entity-framework
I have created simple ASP.NET MVC4 application using EntityFramework Code first approach. The entity class is as below: public class Album { [Key] public int AblumId { get; set; } public decimal Price { get; set; } public string Title { get; set; } } public class MusicContext : DbContext...

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

How to make LINQ to multiple tables

c#,asp.net,linq,entity-framework,code-first
I have two EF entities: Client and Benefit. (In the database they are connected in intermediary table: "ClientsBenefits", if it's important), I connected them in intermediary class "ClientIndexData", as it was adviced on asp.net guides. Could you advice me how to use LINQ to search clients without benefits? I know,...

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

Select query in Entity framwork

entity-framework
I have two models and a dbcontext: public class User { public int UserId { get; set; } public String UserName { get; set; } public virtual ICollection<Conversation> Conversations { get; set; } } public class Conversation { public int ConversationId { get; set; } public String Text { get;...

Difference between cast and as inside a select in LINQ

c#,linq,entity-framework
This code throws exception: var query = services .SomeQuery(bar).select(x => (Foo)x) .Where(x.PropertyOfFoo == FooState.SomeState); var result = query.ToList(); The exception: Unable to cast the type... LINQ to Entities only supports casting EDM primitive or enumeration types. This code works: var query = services .SomeQuery(bar).select(x => x as Foo) .Where(x.PropertyOfFoo ==...

Symfony2 relationship between two entities

php,mysql,entity-framework,symfony2
I want to make a relationship between two entities but for some reason I am getting NULL on one of the values... So in my skin entity I have an email_registration_id field with the relationship : /** * @ORM\ManyToOne(targetEntity="Project\UserBundle\Entity\Email") * @ORM\JoinColumn(name="email_registration_id", referencedColumnName="id") */ protected $email_registration_id; /** * Set email_registration_id *...

N to M relationship code first does not create the foreign key on the M-table

entity-framework,entity-framework-6.1
A SchoolclassCode can have many Pupils. A Pupil can belong to many SchoolclassCodes. This is an N to M relation. I thought N to M relation work in code first by default. But I also explicitly create the N to M relation here: modelBuilder.Entity<SchoolclassCode>(). HasMany(c => c.Pupils). WithMany(p => p.SchoolclassCodes)....

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

How to create edit view with a dropdownlist

c#,asp.net,asp.net-mvc,entity-framework,asp.net-mvc-3
I have the following entities: public class Entidad { [Key] public int Id { get; set; } public string Nombre { get; set; } public virtual ICollection<Propiedad> Propiedades { get; set; } } public class Propiedad { [Key] public int Id { get; set; } public virtual Entidad Entidad {...

Entity Framework + Boolean Matrix

c#,asp.net,entity-framework
My goal is to hold a square (i.e. nxn) BOOLEAN matrix in a database which I can query and modify using the entity framework. I have created a class to model each row of the matrix called MatrixRow. The matrix holds boolean values, I want to be able to select...

EF LINQ - Return entities that contain an entire collection

c#,asp.net,entity-framework,linq-to-entities
I am trying to troubleshoot the following LINQ Query: public JsonResult SearchNodesByTags(string[] tags) { var nodes = _DbContext.Nodes. Where(n => n.Tags.All(t => tags.Contains(t.DisplayName))) .Select(n => new {n.NodeNativeId, n.NodeName, n.NodeClass.ClassName}) .ToList(); return Json(nodes); } The query is returning a single node that is not associated with a tag. What I want...

Downside of using transaction dispose with entity framework integration testing

entity-framework,transactions,entity-framework-6.1
I am looking for a quick way to clean my tables data doing integration tests with EF. Everyone seems to wrap a transaction around its test method and dispose the transaction after the test. That way the data is never written to the table. Things like new auto ids for...

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

EntityFramework 6 / SqlCe 4 SaveChangesAsync()

c#,wpf,multithreading,entity-framework,sqlce
I have the following method running in a non-GUI thread within my application: private async Task PerformContextSubmitAsync() { try { await DataContextProvider.GetDefaultContext().SaveChangesAsync(); } catch (Exception ex) { Log.Error("Error performing context submit", ex); } } Which is called like this: await PerformContextSubmitAsync(); The application is a WPF/Prism based application so I'm...

A specified Include path is not valid. The EntityType '*Propiedad' does not declare a navigation property with the name 'Nombre'

c#,asp.net-mvc,entity-framework,asp.net-mvc-4,repository-pattern
I am trying to implement unit of work and the generic repository pattern as explained here: http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application My entity Propiedad is like this: public class Propiedad { [Key] public int Id { get; set; } public virtual Entidad Entidad { get; set; } public string Codigo { get; set; }...

sqlite query slow, how to optimize (using linq to entities)

c#,linq,entity-framework,sqlite
I have used MS SQL server a few times and have yet to run into a speed issue when querying, using linq to entities. This time, I am using sqlite, as to ship the entire database with the application. I have a winforms app that contains 4 search fields. My...

Related entity not loaded

c#,.net,entity-framework
I'm starting a new entity framework project and I'm defining relations among entities. I defined this simple entities: [Table("db_owner.Students")] public partial class User { [Key] public int Id { get; set; } [Required] [StringLength(50)] public string Name { get; set; } public int? SchoolClassId { get; set; } [ForeignKey("SchoolClassId")] public...

Entity Framework Is Null, Is Not Null Using DB2

c#,entity-framework,db2
I tried this: <pre>var query = this.context.PERFIL_ALERTA.Where(x => x.CodigoEmpresa == EmpresaId && x.IdAtividade == null);<code> But Entity do this: SELECT CAST(NULL AS decimal(18,2)) AS C1, CAST(NULL AS decimal(18,2)) AS C2, CAST(NULL AS decimal(18,2)) AS C3, CAST(NULL AS varchar(1)) AS C4, CAST(NULL AS decimal(18,2)) AS C5, CAST(NULL AS decimal(18,2)) AS C6,...

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

c# auto generated partial class redefine property get set

c#,asp.net-mvc,entity-framework,partial-classes
I'm moving from mainly classic asp to .NET. So this may be a stupid question, but I can't find an answer. I have an MVC App using Database First and Entity Framework. Now I would like to add some logic to the auto generated 'partial' classes. From what I have...

Asp.Net Identity find users not in role

asp.net,linq,entity-framework,asp.net-identity
I need to find all users that DONT'T contain a certain role, using Asp.Net Identity. So far I have something like this but it is not working. (From role In context.Roles From userRoles In role.Users Join us In context.Users On us.Id Equals userRoles.UserId Where role.Name <> "SomeRole" Select us.UserName) This...

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

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

EF: configuring many to many relationship (code first)

entity-framework
In my scenario I have Jobs, Companies and Departments. Single Job may have only one Company; Company may have multiple Jobs (One-To-Many) Single Job may have multiple Departments; Department may have multiple Jobs (Many-To-Many). I want to set relations using Foreign Keys only. For that I have property of Foreign...

Using EF6 code-first, reference same property name

c#,entity-framework,properties,mapping
How to reference both ShippingAddressId and BillingAddressId properties in Customer class to Address class which has a diffrent key named AddressId? Running update-database -verbose causes error: Unable to determine the principal end of an association between the types 'Project1.Customer' and 'Project1.Address'. The principal end of this association must be explicitly...

Two equal pieces of code work differently

c#,asp.net,asp.net-mvc,entity-framework
Working on my project I faced a problem: EF didn't load the data from connected table, but in other practically equal piece of code all is perfect. Can somebody explain it? Here is the situation: All is good, type.name is loaded: [HttpPost] [ValidateAntiForgeryToken] public ActionResult pacientEdit([Bind(Include = "ID,comments")] Anamnesis anamnesis)...