簡體   English   中英

實體框架6 1對1關系映射不起作用

[英]Entity Framework 6 1 to 1 relationship mapping not working

我將Entity Framework 6與現有數據庫一起使用,並已從舊的自定義身份驗證系統遷移了一些數據。

我有兩個模型,一個模型在MVC5中擴展了腳手架的ApplicationUser(身份),另一個模型是舊表的模型。 這些表具有1到1的關系。

因為我的身份驗證表的UserId曾經是一個int,並且ASP.NET Identity 2將ID定義為GUID,所以我使用舊的UserId(這是tbl0102User的主鍵)創建了關聯。

因此表是:

AspNetUsers:

- Id (guid)
- Username etc
- UserId (int) - this is the column I have created on the table to map to the old User table

Tbl01012Users:

 - UserId (int)
 - address etc...

我的兩個模型的代碼是:

 public class ApplicationUser : IdentityUser
    {
        public int UserId { get; set; }

        [ForeignKey("UserId")]
        public UserDetails Details { get; set; }
    }

[Table("tbl0102User")]
public class UserDetails
{
    // This numeric id contains the relationship between the old authentication system and the new ASP.NET Identity.
    // The new system has a Guid as Id, but that is different to the UserId.
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }

    public ApplicationUser AppUser { get; set; }

    public string UserLogin { get { return AppUser.UserName; } }

    // etc....
}

當我嘗試構建並運行該應用程序時,出現以下錯誤:

System.InvalidOperationException: Unable to determine the principal end of an association between the types 'Plus.Models.ApplicationUser' and 'Plus.Models.UserDetails'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
   at System.Data.Entity.ModelConfiguration.Edm.Services.AssociationTypeMappingGenerator.GenerateIndependentAssociationType(AssociationType associationType, DbDatabaseMapping databaseMapping)
   at System.Data.Entity.ModelConfiguration.Edm.Services.DatabaseMappingGenerator.GenerateAssociationTypes(DbDatabaseMapping databaseMapping)
   at System.Data.Entity.ModelConfiguration.Edm.Services.DatabaseMappingGenerator.Generate(EdmModel conceptualModel)
   at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
   at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
   at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
   at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.LazyInternalContext.get_CodeFirstModel()
   at System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext context, XmlWriter writer)
   at System.Data.Entity.Utilities.DbContextExtensions.<>c__DisplayClass1.<GetModel>b__0(XmlWriter w)
   at System.Data.Entity.Utilities.DbContextExtensions.GetModel(Action`1 writeXml)
   at System.Data.Entity.Utilities.DbContextExtensions.GetModel(DbContext context)
   at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext)
   at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
   at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.GetMigrator()
   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)

為什么是這樣? 我已經在ApplicationUser對象上指定了Details屬性的外鍵根據UserDetails對象上的外鍵userId進行映射。

我怎樣才能改變它的工作方式?

我也嘗試了流暢的映射,如: http : //msdn.microsoft.com/en-au/data/jj713564.aspx

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<UserDetails>()
                .HasOptional(t => t.AppUser)
                .WithRequired(t => t.Details)
                ;            
        }

但是得到錯誤:

UserDetails_AppUser_Target: : Multiplicity is not valid in Role 'UserDetails_AppUser_Target' in relationship 'UserDetails_AppUser'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.

我也嘗試過:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<UserDetails>()
                .HasRequired(x=>x.AppUser)
                .WithRequiredDependent(y=>y.Details)               
                ;            
        }

但是,我得到了錯誤:

UserDetails_AppUser_Target_UserDetails_AppUser_Source: : The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role. The type of property 'UserId' on entity 'UserDetails' does not match the type of property 'Id' on entity 'ApplicationUser' in the referential constraint 'UserDetails_AppUser'.

對我來說,這表示它未正確選擇ApplicationUser上的外鍵,而是使用主鍵ID(guid)。

您可以嘗試指定外鍵,如下所示:

public class ApplicationUser : IdentityUser
{
    [ForeignKey("UserDetails")]
    public int UserId { get; set; }

    public UserDetails Details { get; set; }
}

另一個選擇是在UserDetails中的ApplicationUser屬性上使用Required屬性。

我找到了答案:

public class ApplicationUser : IdentityUser
{
    public int UserId { get; set; }

    [ForeignKey("UserId")]
    public virtual UserDetails Details { get; set; }
}

除了將UserDetails對象標記為虛擬對象外,我不確定這與原始版本有何不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM