0

我有一个实体组,它与视图 VesselInfo 具有多对多关系。在数据库中,关系存储在一个表 GroupVessel 中。

public class Group
{
    public Group()
    {
        GroupVessels = new List<GroupVessel>();
    }

    public int GroupId { get; set; }

    public virtual ICollection<GroupVessel> GroupVessels { get; set; }
}

public class GroupVessel
{
    public int GroupVesselId { get; set; }

    public int GroupId { get; set; }
    public virtual Group Group { get; set; }

    public int VesselId { get; set; }
    public virtual VesselView Vessel { get; set; }
}

public class VesselView
{
    public int VesselId { get; set; }
}

实体在上下文中映射如下:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new VesselViewMapping());
    modelBuilder.Configurations.Add(new GroupMapping());
    modelBuilder.Configurations.Add(new GroupVesselMapping());
    base.OnModelCreating(modelBuilder);
}

public class VesselViewMapping : EntityTypeConfiguration<VesselView>
{
    public VesselViewMapping()
    {
        // Primary Key
        HasKey(t => t.VesselId);

        // Properties
        Property(t => t.VesselId)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

        // Table & Column Mappings
        ToTable("v_VesselInfo");
        Property(t => t.VesselId).HasColumnName("VesselId");
    }
}

public class GroupMapping : EntityTypeConfiguration<Group>
{
    public GroupMapping()
    {
        // Primary Key
        HasKey(group => group.GroupId);

        // Properties

        // Table & Column Mappings
        ToTable("Group");
        Property(t => t.GroupId)
            .HasColumnName("GroupId")
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}

public class GroupVesselMapping : EntityTypeConfiguration<GroupVessel>
{
    public GroupVesselMapping()
    {
        // Primary Key
        HasKey(group => group.GroupVesselId);

        // Properties

        // Table & Column Mappings
        ToTable("GroupVessel");
        Property(t => t.GroupVesselId)
            .HasColumnName("GroupVesselId")
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        Property(t => t.VesselId).HasColumnName("VesselId").IsRequired();

        Property(t => t.GroupId).HasColumnName("GroupId");

        // Relationships
        HasRequired(t => t.Group).WithMany(g => g.GroupVessels)
                                 .HasForeignKey(t => t.GroupVesselId);
    }
}

当我尝试实例化上下文时,出现以下错误:

异常详细信息:System.Data.Entity.ModelConfiguration.ModelValidationException:在模型生成期间检测到一个或多个验证错误:

\tSystem.Data.Entity.Edm.EdmAssociationEnd: : 多重性在关系“GroupVessel_Group”中的角色“GroupVessel_Group_Source”中无效。因为从属角色指的是关键属性,所以从属角色的多重性的上限必须是“1”。

一些附加信息: 在数据库中,GroupVessel.VesselId 列是表 Vessels 的外键,该表是 v_VesselInfo 视图的基础表。没有从 VesselView 返回到 GroupVessel 的导航属性,因为无需在应用程序中以这种方式遍历图形。

4

1 回答 1

0

终于弄明白了,我用错了字段作为外键字段,改成GroupId就可以了

于 2013-11-13T12:39:21.920 回答