EF code-first: Sequence contains more than one mat

2019-07-15 19:32发布

问题:

I'm using EF6 code-first, and have a User class that needs to have incoming and outgoing connections to other users. A connection also has properties, so I also have a Connections class.

public class User
{
    public int ID { get; set; }

    // Other properties removed here to keep it simple

    [InverseProperty("SourceUser")]
    public virtual ICollection<Connection> OutgoingConnections { get; set; }

    [InverseProperty("DestUser")]
    public virtual ICollection<Connection> IncomingConnections { get; set; }
}

public class Connection
{
    public int ID { get; set; }

    // Other properties removed here to keep it simple

    [InverseProperty("OutgoingConnections")]
    public User SourceUser { get; set; }

    [InverseProperty("IncomingConnections")]
    public User DestUser { get; set; }
}

I'm getting the following error when updating my database. Initially I didn't have the InverseProperty attributes, so I can understand why EF didn't know what to do in that case. The documentation sounds like these attributes are what I want though - but it's still not working. Perhaps I'm misunderstanding it though.

I want to end up with a Users table, and a Connections table where the Connections table has ID, SourceUserID, DestUserID (obviously with FK constraints).

Any ideas?

Specify the '-Verbose' flag to view the SQL statements being applied to the target database. Applying explicit migrations: [201411192045091_InitialCreate]. Applying explicit migration: 201411192045091_InitialCreate. System.InvalidOperationException: Sequence contains more than one matching element at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable1 source, Func2 predicate) at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.<>c__DisplayClass250.b__247(<>f__AnonymousType2b2 <>h__TransparentIdentifier242) at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()
at System.Collections.Generic.List
1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable
1 source) at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(ModelMetadata source, ModelMetadata target, Lazy1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion) at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, Lazy1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion) at System.Data.Entity.Migrations.DbMigrator.IsModelOutOfDate(XDocument model, DbMigration lastMigration) at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable
1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration) at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.b__b() at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration) at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run() at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate) at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner) at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force) at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0() at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command) Sequence contains more than one matching element

回答1:

Sorry if using InverseProperties is a requirement but the relationships can be done this way if you have the flexibility to wire them up differently.

public class User
{
    public int ID { get; set; }

    [ForeignKey("ID")]
    public virtual ICollection<Connection> OutgoingConnections { get; set; }

    [ForeignKey("ID")]
    public virtual ICollection<Connection> IncomingConnections { get; set; }
}

public class Connection
{
    public int ID { get; set; }

    public int SourcerId {get;set;}

    public int DestUserId {get;set;}

    [ForeignKey("SourcerId")]
    public User SourceUser { get; set; }

     [ForeignKey("DestUserId")]
    public User DestUser { get; set; }
}

then you need to add configurations. In my case to test this I did it in protected override void OnModelCreating(DbModelBuilder modelBuilder) in the context.

    modelBuilder.Entity<User>().HasMany(x=>x.IncomingConnections).WithRequired(x=>x.SourceUser).WillCascadeOnDelete(false);
    modelBuilder.Entity<User>().HasMany(x => x.OutgoingConnections).WithRequired(x => x.DestUser).WillCascadeOnDelete(false);