我創建一個表像這樣:MVC5引用的Guid
public class Team
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public string CaptainId { get; set; }
public string CoCaptainId { get; set; }
public string ContactDetails { get; set; }
}
然後,我有一個表像這樣:
public class TeamMember
{
public string Id { get; set; }
public string Description { get; set; }
public string GameDisplayName { get; set; }
public DateTime Joined { get; set; }
public string TeamId { get; set; }
}
我有2個問題,我不周圍EF 6理解和MVC5。
1)如何在Team表中引用我的Id字段。我是否將TeamId作爲字符串或Guid設置在TeamMember中?我知道我需要設置屬性[ForeignKey("Team")]
,但我仍然不明白如何在代碼中正確引用它,因爲無論何時需要進行任何類型的比較,我都必須在Guid上輸入.ToString()
才能夠獲得與另一個字符串值進行比較的值。
2)我的TeamMember也有一個Id,並且此Id在Identity框架中引用用戶。我應該如何引用那個,Id是爲了引用用戶表中的Id的外鍵,但我不知道如何正確地引用那個,它是像我這樣做的字符串,還是Guid或某個東西其他?
編輯:
public class Team
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public Guid CaptainId { get; set; }
public Guid CoCaptainId { get; set; }
}
public class TeamMember
{
public Guid MemberId { get; set; }
public string TeamId { get; set; }
public virtual Team Team { get; set; }
public virtual Member Member { get; set; }
}
public class Member : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string About { get; set; }
public string Alias { get; set; }
public string CustomUrl { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<Member> 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;
}
}
public class ApplicationDbContext : IdentityDbContext<Member>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public DbSet<Team> Teams { get; set; }
public DbSet<TeamMember> TeamMembers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUserClaim>().ToTable("MemberClaim");
modelBuilder.Entity<IdentityUserRole>().ToTable("MemberRole");
modelBuilder.Entity<IdentityUserLogin>().ToTable("MemberLogin");
modelBuilder.Entity<IdentityRole>().ToTable("Role");
modelBuilder.Entity<Member>().ToTable("Member");
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
錯誤,我得到:
var user = new Member { UserName = model.Email, Email = model.Email, CustomUrl = model.CustomUrl, Alias = model.Alias};
var team = new Team {CaptainId = user.Id, Created = currentTime, IsSingleMember = true};
CaptainId = user.Id gives an error:
Cannot convert source type 'string' to target type 'System.Guid'
應該儘量保持一致性;如果您要將Guid/uniqueidentifier用作一個表的主鍵,請在其他表上使用相同的列類型。 –