entity-framework,foreign-keys , Entity Frame Code First The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical


Entity Frame Code First The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical

Question:

Tag: entity-framework,foreign-keys

Database build error:

One or more validation errors were detected during model generation:

AccountLinkPermission_AccountLink_Target_AccountLinkPermission_AccountLink_Source: : The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical.

User class:

public class User
{
    public User()
    {
        AccountLinks = new HashSet<AccountLink>();
    }

    [Key]
    public int UserID { get; set; }

    public virtual ICollection<AccountLink> AccountLinks { get; set; }
}

Guest class:

public class Guest
{
    public Guest()
    {
        AccountLinks = new HashSet<AccountLink>();
    }

    [Key]
    public int GuestID { get; set; }

    public virtual ICollection<AccountLink> AccountLinks { get; set; }
}

AccountLink class:

public class AccountLink
    {
        public AccountLink()
        {
            AccountLinkPermissions = new HashSet<AccountLinkPermission>();
        }

        public AccountLink(int userID, int guestID)
        {
            this.UserID = userID;
            this.GuestID = guestID;
        }

        [Key, Column(Order = 0)]
        public int AccountLinkID { get; set; }
        [Key, Column(Order = 1)]
        public int UserID { get; set; }
        [Key, Column(Order = 2)]
        public int GuestID { get; set; }

        [ForeignKey("UserID")]
        public virtual User User { get; set; }

        [ForeignKey("GuestID")]
        public virtual Guest Guest { get; set; }

        public virtual ICollection<AccountLinkPermission> AccountLinkPermissions { get; set; }
    }

AccountLinkPermission class:

public class AccountLinkPermission
{
    public AccountLinkPermission(int accountLinkID, int permissionID)
    {
        this.AccountLinkID = accountLinkID;
        this.PermissionID = permissionID;
    }

    [Key, Column(Order = 0)]
    public int AccountLinkID { get; set; }
    [Key, Column(Order = 1)]
    public int PermissionID { get; set; }

    [ForeignKey("AccountLinkID")]
    public virtual AccountLink AccountLink { get; set; }

    [ForeignKey("PermissionID")]
    public virtual Permission Permission { get; set; }
}

Permission class:

public class Permission
{
    public Permission()
    {
        AccountLinkPermissions = new HashSet<AccountLinkPermission>();
    }

    [Key]
    public int PermissionID { get; set; }
    public string Name { get; set; }

    public virtual ICollection<AccountLinkPermission> AccountLinkPermissions { get; set; }
}

Problem:

It wont let me put a foreign key between AccountLinkPermission, AccountLinkID and AccountLink, AccountLinkID. If I remove the ForeignKey attribute the database builds, but without a foreign key between these two.

Why in world is this not working? It's driving me crazy. PLEASE please help me..


Answer:

The reason why I got this error message was because AccountLink had three primary keys. Because I was only declaring one foreign key from AccountLinkPermission to AccountLink, (AccountLinkID), it failed. I had to set Foreignkey for UserID and GuestID aswell.

Also, if you are using multiple foreign keys linked to the same table, EF is not able to determine by convention which navigation properties belongs together. Instead of using the property [ForeignKey] I had to use [InverseProperty], which defines the navigation property on the other end of the relationship.

Heres what's changed:

AccountLink:

public class AccountLink
{
    public AccountLink()
    {
        AccountLinkPermissionAccountLinkID = new HashSet<AccountLinkPermission>();
        AccountLinkPermissionUserID = new HashSet<AccountLinkPermission>();
        AccountLinkPermissionGuestID = new HashSet<AccountLinkPermission>();
    }

    public AccountLink(int userID, int guestID)
    {
        AccountLinkPermissionAccountLinkID = new HashSet<AccountLinkPermission>();
        AccountLinkPermissionUserID = new HashSet<AccountLinkPermission>();
        AccountLinkPermissionGuestID = new HashSet<AccountLinkPermission>();
        this.UserID = userID;
        this.GuestID = guestID;
    }

    [Key, Column(Order = 0)]
    public int AccountLinkID { get; set; }
    [Key, Column(Order = 1)]
    public int UserID { get; set; }
    [Key, Column(Order = 2)]
    public int GuestID { get; set; }

    [ForeignKey("UserID")]
    public virtual User User { get; set; }

    [ForeignKey("GuestID")]
    public virtual Guest Guest { get; set; }

    public virtual ICollection<AccountLinkPermission> AccountLinkPermissionAccountLinkID { get; set; }
    public virtual ICollection<AccountLinkPermission> AccountLinkPermissionUserID { get; set; }
    public virtual ICollection<AccountLinkPermission> AccountLinkPermissionGuestID { get; set; }
}

AccountLinkPermission:

public class AccountLinkPermission
        {
            public AccountLinkPermission(int accountLinkID, int userID, int guestID, int permissionID)
            {
                this.AccountLinkID = accountLinkID;
                this.UserID = userID;
                this.GuestID = guestID;
                this.PermissionID = permissionID;
            }

            [Key, Column(Order = 0)]
            public int AccountLinkID { get; set; }
            [Key, Column(Order = 1)]
            public int UserID { get; set; }
            [Key, Column(Order = 2)]
            public int GuestID { get; set; }
            [Key, Column(Order = 3)]
            public int PermissionID { get; set; }

            [InverseProperty("AccountLinkPermissionAccountLinkID")]
            public virtual AccountLink AccountLink { get; set; }

            [InverseProperty("AccountLinkPermissionUserID")]
            public virtual AccountLink AccountLinkUser { get; set; }

            [InverseProperty("AccountLinkPermissionGuestID")]
            public virtual AccountLink AccountLinkGuest { get; set; }

            [ForeignKey("PermissionID")]
            public virtual Permission Permission { get; set; }
        }

Related:


MySQL structural integrity versus simplicity?


php,mysql,foreign-keys,referential-integrity
My problem: On a PHP/MySQL application I have to distinguish the registered accounts from the simple visitors. Both of them can perform actions which are written into the database. Now I use a separate table for visitors and a separate table for registered accounts. My example solutions so far: Option...

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

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

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

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

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

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

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

SQL alchemy - specifying relationships when foreign key may not exist


python,sqlalchemy,foreign-keys
I need to set up two tables in a database and I'm struggling to decide how to design the tables in SQL Alchemy. Table 1 contains raw address data, and the source of the address. Raw addresses may appear more than once if they come from different sources. Table 2...

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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