我正在尝试使用Entityframework codefirst方法与webapi2应用程序实现多对多的关系。
问题:未在第三个表格中插入值。
其他信息:
如果我正在使用非会员表,它的工作正常。但是当我使用ApplicationUser表(即实体框架创建的表)进行映射时,插入不会发生。我在此applicationuser表中使用了承载令牌身份验证,并根据我的requiremnet添加了一些自定义列。我提到了以下链接
问题:
我们可以与其他表格建立会员资格(用户,角色)的多对多关系吗?
代码我尝试过:
模型1
public class Strata
{
[Key]
public Guid StrataID { get; set; }
public string StrataNumber { get; set; }
public string StrataName { get; set; }
public string StrataType { get; set; }
public int NumberOfUnits { get; set; }
public string StreetAddress { get; set; }
public string City { get; set; }
public string Province { get; set; }
[Required(ErrorMessage = "Country required")]
public string Country { get; set; }
[Required(ErrorMessage = "Zip code required")]
public string ZipCode { get; set; }
public string VerificationCode { get; set; }
public bool IsActive { get; set; }
public bool? IsConfirmed { get; set; }
public string UserId { get; set; }
[DataType(DataType.Date)]
public DateTime SubscriptionStartDate { get; set; }
[DataType(DataType.Date)]
public DateTime SubscriptionEndDate { get; set; }
public int PaymentId { get; set; }
public double Amount { get; set; }
public string SubscriptionType { get; set; }
public bool PaymentStatus { get; set; }
public virtual ICollection<ApplicationUser> ApplicationUsers { get; set; }
public Strata()
{
ApplicationUsers = new List<ApplicationUser>();
}
}
模型2
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
// Add custom user claims here
return userIdentity;
}
public ApplicationUser()
{
Stratas = new List<Strata>();
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string ConfirmEmailAddress { get; set; }
public bool IsActive { get; set; }
public string CurrentStatus { get; set; }
public string TypeOfUser { get; set; }
public bool ResetFlag { get; set; }
public virtual ICollection<Strata> Stratas
{
get;
set;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DbContextCondo", throwIfV1Schema: false)
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder); // This needs to go before the other rules!
//modelBuilder.Entity<ApplicationUser>().ToTable("User");
modelBuilder.Configurations.Add(new UserMap());
modelBuilder.Configurations.Add(new StrataMap());
modelBuilder.Entity<IdentityRole>().ToTable("Role");
modelBuilder.Entity<IdentityUserRole>().ToTable("UserRole");
modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaim");
modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogin");
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public DbSet<Strata> Strata { get; set; }
}
地图1
public class UserMap : EntityTypeConfiguration<ApplicationUser>
{
public UserMap()
{
//Primary Key
this.HasKey(t => t.Id);
this.Property(t => t.FirstName).HasColumnName("FirstName");
this.Property(t => t.LastName).HasColumnName("LastName");
this.Property(t => t.ConfirmEmailAddress).HasColumnName("ConfirmEmailAddress");
this.Property(t => t.IsActive).HasColumnName("IsActive");
this.Property(t => t.CurrentStatus).HasColumnName("CurrentStatus");
this.Property(t => t.TypeOfUser).HasColumnName("TypeOfUser");
this.Property(t => t.ResetFlag).HasColumnName("ResetFlag");
// Relationships
this.HasMany(t => t.Stratas)
.WithMany(t => t.ApplicationUsers)
.Map(m =>
{
m.ToTable("UsersStratas");
m.MapLeftKey("Id");
m.MapRightKey("StrataID");
});
}
}
地图2
public class StrataMap: EntityTypeConfiguration<Strata>
{
public StrataMap()
{
//Primary Key
this.HasKey(t => t.StrataID);
this.Property(t => t.StrataID).HasColumnName("StrataID");
this.Property(t => t.StrataNumber).HasColumnName("StrataNumber");
this.Property(t => t.StrataType).HasColumnName("StrataType");
this.Property(t => t.NumberOfUnits).HasColumnName("NumberOfUnits");
this.Property(t => t.StreetAddress).HasColumnName("StreetAddress");
this.Property(t => t.City).HasColumnName("City");
this.Property(t => t.Province).HasColumnName("Province");
this.Property(t => t.Country).HasColumnName("Country");
this.Property(t => t.ZipCode).HasColumnName("ZipCode");
this.Property(t => t.VerificationCode).HasColumnName("VerificationCode");
this.Property(t => t.IsActive).HasColumnName("IsActive");
this.Property(t => t.IsConfirmed).HasColumnName("IsConfirmed");
this.Property(t => t.UserId).HasColumnName("UserId");
this.Property(t => t.SubscriptionStartDate).HasColumnName("SubscriptionStartDate");
this.Property(t => t.SubscriptionEndDate).HasColumnName("SubscriptionEndDate");
this.Property(t => t.PaymentId).HasColumnName("PaymentId");
this.Property(t => t.Amount).HasColumnName("Amount");
this.Property(t => t.SubscriptionType).HasColumnName("SubscriptionType");
this.Property(t => t.PaymentStatus).HasColumnName("PaymentStatus");
}
}
控制器
public IHttpActionResult PostStrata(Strata strata)
{
DTOStrata strataInfo = new DTOStrata();
try
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
strata.StrataID = Guid.NewGuid();
strata.SubscriptionStartDate = Convert.ToDateTime(DateTime.Now.ToShortDateString().ToString());
if (strata.SubscriptionType == "Invoice Monthly")
{
strata.SubscriptionEndDate = Convert.ToDateTime(DateTime.Now.AddMonths(6).ToShortDateString().ToString());
}
else
{
strata.SubscriptionEndDate = Convert.ToDateTime(DateTime.Now.AddMonths(12).ToShortDateString().ToString());
}
strata.IsActive = true;
strata.PaymentId = 1;
strata.IsConfirmed = false;
var verificationCode = VerificationCodeGenerator.GenerateOTP(6);
strata.VerificationCode = verificationCode;
db.Strata.Add(strata);
db.SaveChanges();
}
如果我错过了代码中的任何内容,请告诉我。或者建议我采用更好的方法。
由于 开发
答案 0 :(得分:0)
你的OnModelCreating
方法是什么样的?
映射代码应该在dbContext
的此方法中引入,请查看:
Configure Many-to-Many relationship
但如果您想使用EntityTypeConfiguration
进行映射,是否已将配置添加到模型中?为此,您必须在OnModelCreating
中的dbContext
方法中使用此代码:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new UserMap());
}
要获得样本,请查看以下内容: Using the Code First Model ConfigurationClasses