关于MVC3中EF关系的问题

时间:2012-02-09 08:46:08

标签: linq asp.net-mvc-3 entity-framework-4 model

我收到了以下代码:

public class Trip
{
    public int TripId { get; set; }

    public int DriverId { get; set; }

    public string StartingPoint { get; set; }

    public string Destination { get; set; }

    public DateTime TimeDepart { get; set; }

    public int SeatAvailable { get; set; }

    public virtual Carpooler Carpooler { get; set; }

    public virtual ICollection<Passenger> Passengers { get; set; }
}

public class Driver
{
    public int DriverId { get; set; }

    public int TripId { get; set; }

    public virtual Trip Trip { get; set; }
}

public class Passenger
{
    public int PassengerId { get; set; }

    public int TripId { get; set; }

    public virtual Trip Trip { get; set; }
}

模型构建器:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        //one-to-one between Trip and Carpooler
        modelBuilder.Entity<Trip>()
            .HasRequired(x => x.Carpooler)
            .WithRequiredDependent();
        modelBuilder.Entity<Carpooler>()
            .HasRequired(x => x.Trip)
            .WithRequiredPrincipal();
        base.OnModelCreating(modelBuilder);

        //zero or one-to-many between Trip and Passenger
        modelBuilder.Entity<Trip>()
        .HasOptional(x => x.Passengers);

        modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
    }

初始值设定项:

Database.SetInitializer<LiveGreenContext>(new CarpoolTripInitializer());

我收到以下错误: Multiplicity在关系'Trip_Driver'中的角色'Trip_Driver_Target'中无效。由于Dependent Role属性不是关键属性,因此Dependent Role的多重性的上限必须为*。

问题的任何解决方案?谢谢!

1 个答案:

答案 0 :(得分:0)

配置TripDriver之间的关系。 DriverId中的Trip属性未配置。如果您打算将其用作导航属性,则还需要对其进行配置。

您的OnModelCreating方法中的某些配置不完整,已得到纠正。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Driver>()
        .HasRequired(x => x.Trip)
        .WithMany()
        .HasForeignKey(x => x.TripId);

    //one-to-one between Trip and Carpooler
    modelBuilder.Entity<Trip>()
        .HasRequired(x => x.Carpooler)
        .WithRequiredDependent();

    modelBuilder.Entity<Carpooler>()
        .HasRequired(x => x.Trip)
        .WithRequiredPrincipal();

    //zero or one-to-many between Trip and Passenger
    modelBuilder.Entity<Trip>()
    .HasMany(x => x.Passengers)
    .WithRequired(x => x.Trip)
    .HasForeignKey(x => x.TripId);

    base.OnModelCreating(modelBuilder);

    modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
}