EntityFramework core model relationship issue while doing Add-Migration

核能气质少年 提交于 2019-12-12 03:53:30

问题


I am facing an EntityFramework core model relation issue while doing migration using Package Manager Console in a asp.net core project.

Getting below error while adding migration "Add-Migration".

Unable to determine the relationship represented by navigation property 'College.Users' of type 'ICollection'. Either manually configure the relationship, or ignore this property from the model.

Full Error

System.InvalidOperationException: Unable to determine the relationship represented by navigation property 'College.Users' of type 'ICollection'. Either manually configure the relationship, or ignore this property from the model. at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.PropertyMappingValidationConvention.Apply(InternalModelBuilder modelBuilder) at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelBuilt(InternalModelBuilder modelBuilder) at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator) at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory) at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel() at Microsoft.EntityFrameworkCore.Internal.LazyRef1.get_Value() at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitTransient(TransientCallSite transientCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitTransient(TransientCallSite transientCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_01.b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) Unable to determine the relationship represented by navigation property 'College.Users' of type 'ICollection'. Either manually configure the relationship, or ignore this property from the model.

I have following models

public class College
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("name")]
    public string CollegeName { get; set; }

    [ForeignKey("Users")]
    [JsonProperty("users")]
    public ICollection<User> Users { get; set; }
}

public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("name")]
    public string UserName { get; set; }

    [JsonProperty("email")]
    public string UserEmail { get; set; }

    [JsonProperty("phone")]
    public string UserPhone { get; set; }

    [ForeignKey("CollegeId")]
    [JsonProperty("college")]
    public College College{ get; set; }
}

Please anyone throw some light on the issue.

Thanks


回答1:


Short answer: You're using the ForeignKey attribute wrong. Remove it and your migration should start working:

public class College
{
    public int Id { get; set; }
    public string CollegeName { get; set; }
    public ICollection<User> Users { get; set; }
}

public class User
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public string UserEmail { get; set; }
    public string UserPhone { get; set; }
    public College College{ get; set; }
}

Long answer: In your example you're leaving out the foreign key ID property on your models. Instead you are only including the navigation property. By convention you can include the foreign key property by naming it the same as the class you are referring to and adding an ID at the end. In your example that would be:

public int CollegeId {get;set;}

The ForeignKeyAttribute can be used if you don't want to follow this convention. Lets say for example that you wanted to name the property PrimaryCollegeId instead. You could do that by using the ForeignKeyAttribute like this:

public int PrimaryCollegeId {get;set;}
[ForeignKey("PrimaryCollegeId")]
public College College {get;set;}

Usually the ForeignKeyAttribute is used if you have multiple relations between the same tables. For example if the student had a primary and secondary college both as foreign keys.



来源:https://stackoverflow.com/questions/41032192/entityframework-core-model-relationship-issue-while-doing-add-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!