2015-04-24 118 views
0

我在嘗試創建0..1到0..1之間的關係時遇到問題 在AspNetUsers之間首先使用代碼表擴展了applicationuser類和MovieModel。 關係的性質是用戶可以租借一部電影或不租用,並且電影可以租借給一個租戶或不租用。每個實體都可以自立 並且在沒有電影租或承租人的洋田只是nullsMVC 5無法確定0..1到0..1之間的關聯主體關係

我的模型:

public class MovieModel 
    { 
     [Key] 
     public int MovieId { get; set; } 

     [Required] 
     [StringLength(50)] 
     [Column(TypeName="varchar")] 
     [Display(Name = "Movie Name")] 
     public string MovieName { get; set; } 
     [Display(Name = "Release Year")] 


     public string RenterId { get; set; } 

     [ForeignKey("RenterId")] 
     public virtual ApplicationUser Renter { get; set; } 

ApplicationUser類

public class ApplicationUser : IdentityUser 
{ 

    public int? MovieId { get; set; } 
    [ForeignKey("MovieId")] 
    public virtual MovieModel Movie{ get; set; } 

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) 
    { 
     // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 
     var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 
     // Add custom user claims here 
     return userIdentity; 
    } 
} 

按道理它應該工作。有兩個外鍵。在ApplicationUser類(AspNetUser表),並在MovieModel

一個外鍵的外鍵不知怎的,我得到增加遷移此錯誤:Unable to determine the principal end of an association between the types 'VideoLibrary.Models.ApplicationUser' and 'VideoLibrary.Models.MovieModel'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotation

爲什麼會出現這樣那樣的錯誤?我不需要關係中的主體。他們都可以獨自一人。

在此先感謝

回答

1

EF Code First支持1:1和1:0..1的關係。也許你應該嘗試「一到零」。

我刪除了數據註釋並由模型構建器創建它。

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<AllesVersUser>() 
     .HasOptional<MovieModel>(l => l.Movie) 
     .WithOptionalDependent(c => c.Renter) 
     .Map(p => p.MapKey("MovieId")); 

    base.OnModelCreating(modelBuilder); 
} 

試過這在我的解決方案,我可以有電影沒有租客,沒有電影的用戶。

+0

謝謝!我最終使用你的代碼得到了它的工作,但我必須刪除並重新創建數據庫。它可以幫助我理解EF如何工作。 –