entity-framework,entity-framework-6 , many to many with order

many to many with order


Tag: entity-framework,entity-framework-6

I am using this:

.HasMany(u => u.Ys)
.Map(m =>

to model a many to many relationship between X and Y. Is there a way to add an order to this like this:

XId Yid Order
1   2   1
1   3   2


Basically what you want to do is this:

public class XY
    public int XId {get; set;}
    public virtual X X{get; set;}
    public int YId {get; set;}
    public virtual Y Y {get; set;}
    public int Order {get; set;}

and in your modelBuilder:

    .HasMany(x => x.Y)
    .HasForeignKey(k => k.YId);

    .HasMany(y => y.X)
    .HasForeignKey(k => k.XId);


How to map between two entities before paging

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

Unable to find the auto created Database

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 MVC second run error

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

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

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

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

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

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

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

EF Migrations - should an initial migration be automatically generated?

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

EntityFramework 6 / SqlCe 4 SaveChangesAsync()

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

Viewmodel binding for Edit View

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

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

How does the Take() method work in LINQ

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

Difference between cast and as inside a select in LINQ

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

Passing conditional parameters to Database.SqlQuery

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

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

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 to avoid async/await deadlock when blocking is required

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

Foreign key not updating in entity frame work

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

Managing per form ObjectContext lifetime

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

How to set default length on all fields in entity framework 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....

When are Entity instances automatically attached to a context?

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

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

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

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

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

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

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

EF: configuring many to many relationship (code first)

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

Entity Framework - How to get Standard Deviation using GroupBy?

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

Using SqlQuery in 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...

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

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

Get a single text value using linq

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

how to use where with list of string

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

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

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

ED Code First One to Many Relationship Issue - ASP Identity

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

Updating entity framework model using Linq

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

Should i validate if related entity exists before insert?

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

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

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

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

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

Asp.Net Identity find users not in role

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

ASP.NET EF6 - 2 Tables & 1 Link Table

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

Sort a LINQ with another LINQ in MVC

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

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

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

Error while connecting to database in code-first Entity Framework

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

Select query in Entity framwork

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

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

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 solve error in Configuration.cs in code first migration

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

Database object with different data

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

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

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

Related entity not loaded

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

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

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

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

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