0
votes

I have the following classes in an Entity Framework 4.3 Code-First Model for MVC3:

public class Film
{
    public Int32 ID { get; set; }

    [Column("FilmName"), MinLength(2), MaxLength(100)]
    [Required(ErrorMessage = "Please enter a name")]
    public String Name { get; set; }

    public Model.Cast Cast { get; set; }
}

public class Actor
{
    public Int32 ID { get; set; }

    [MaxLength(75)]
    public String Name { get; set; }
}

[Table("Cast")]
public class Cast
{
    public Actor Actor { get; set; }

    [MaxLength(500)]
    public String Role { get; set; }

    public virtual Film Film { get; set; }
}

I want a table layout as follows to result:

Films:
ID PK
Name

Cast:
FilmID PK FK
ActorID PK FK
Role

Actors:
ID PK
Name

How can I get the Cast table to be created? I get the following error at the moment:

##System.Data.Entity.Edm.EdmEntityType: : EntityType 'Cast' has no key defined. Define the key for this EntityType. \tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'Casts' is based on type 'Cast' that has no keys defined.##

But I dont want to create an ID key, I want to use the ID fields of Film and Actor to make a composite primary key, both of which are Foreign Keys to the other tables.

What should I do?

2

2 Answers

0
votes

You must redefine your model this way:

public class Film
{
    public Int32 ID { get; set; }

    [Column("FilmName"), MinLength(2), MaxLength(100)]
    [Required(ErrorMessage = "Please enter a name")]
    public String Name { get; set; }

    public ICollection<Model.Cast> Cast { get; set; }
}

public class Actor
{
    public Int32 ID { get; set; }

    [MaxLength(75)]
    public String Name { get; set; }


    public ICollection<Model.Cast> Cast { get; set; }
}

[Table("Cast")]
public class Cast
{
    [Key, Column(Order = 0)]
    public int ActorId { get; set; }
    [Key, Column(Order = 1)]
    public int FilmId { get; set; }

    [MaxLength(500)]
    public String Role { get; set; }

    [ForeignKey("ActorId")]
    public Actor Actor { get; set; }
    [ForeignKey("FilmId")]
    public virtual Film Film { get; set; }
}
0
votes

I've tried to do this before with no success. My solution was map the link table like a normal entity with it's own identity PK and customize the DatabaseInitializer to run a DDL script to create an Unique Index for the FK's. I guess EF wasn't design to support this kind of legacy mapping.