因此,我尝试使用 MVC 4 互联网应用程序模板及其为帐户创建的 UserProfile
数据库表,然后添加依赖于 UserProfile
表的表获取更多信息。
模型将是UserProfile 0 ---> 1 UserType1 和 UserProfile 0 ----> UserType2
其中,用户配置文件表可能在 UserType1
中具有依赖记录,并且在 UserType2
中可能具有依赖记录,并且如果在 UserType1
或UserType2
其主键是外键,即用户配置文件中的 UserId
POCO 是:
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public int type { get; set; }
public virtual UserType1 UserType1 { get; set; }
public virtual UserType2 UserType2 { get; set; }
public class UserType1
{
[key,ForeignKey("UserProfile")]
public virtual int UserId {get;set;}
public int myval {get;set;}
public UserProfile UserProfile {get; set;}
}
public class UserType2 //same as usertype 1
我尝试添加模型映射语句但无济于事
用户配置文件的模型映射数据:
public class UserProfileMap : EntityTypeConfiguration<UserProfile>
{
public UserProfileMap()
{
// Primary Key
this.HasKey(t => t.UserId);
// Properties
this.Property(t => t.Email)
.IsRequired()
.HasMaxLength(56);
this.Property(t => t.UserName)
.IsRequired()
.HasMaxLength(50);
// Table & Column Mappings
this.ToTable("UserProfile");
this.Property(t => t.UserId).HasColumnName("UserId");
this.Property(t => t.Email).HasColumnName("Email");
this.Property(t => t.UserName).HasColumnName("UserName");
this.Property(t => t.UserType).HasColumnName("UserType");
this.HasOptional(e => e.UserType1).WithRequired();
用户类型的模型映射数据如下所示:
public class UserType1 : EntityTypeConfiguration<UserType1>
{
public UserType1Map()
{
// Primary Key
this.HasKey(t => t.UserId);
// Properties
this.Property(t => t.UserId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.HasRequired(t => t.UserProfile).WithOptional();
this.Property(t => t.Company)
.IsRequired()
.HasMaxLength(50);
// Table & Column Mappings
this.ToTable("UserType1");
this.Property(t => t.UserId).HasColumnName("UserId");
this.Property(t => t.Company).HasColumnName("Company");
// Relationships
this.HasRequired(t => t.UserProfile).WithOptional();
}
}
但我总是收到此错误无法确定类型“myApp.Models.UserType1”和“myApp.Models.UserProfile”之间关联的主体端。此关联的主体必须使用关系流畅 API 或数据注释显式配置。
我错过了什么?
最佳答案
仅为一个实体配置关系(在您的情况下,在 UserProfileMap
中)。还要在 .WithRequired()
调用中显式指定该属性。这是对我有用的演示代码:
modelBuilder.Entity<SharedKeyRequired>()
.HasOptional( skr => skr.SharedKeyOptional )
.WithRequired( sko => sko.SharedKeyRequired );
public class SharedKeyRequired
{
public int SharedKeyRequiredId { get; set; }
public virtual SharedKeyOptional SharedKeyOptional { get; set; }
}
public class SharedKeyOptional
{
public int SharedKeyOptionalId { get; set; }
public virtual SharedKeyRequired SharedKeyRequired { get; set; }
}
关于entity-framework - Entity Framework 代码第一个问题无法确定类型之间关联的主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21976541/