Question

I'm using Entity Framework 4.3 with a simple design:

public class Post
{
    [Key]
    public int ID { get; set; }

    public string Text { get; set; }

    public HashSet<PostTag> Tags { get; set; }
}

public class PostTag
{
    public Post Post { get; set; }

    [Key, Column(Order=0)]
    [ForeignKey("Post")]
    public int PostID { get; set; }

    [Key, Column(Order=1)]
    [MaxLength(50)]
    public string Tag { get; set; }
}

So you can see a Post has multiple tags, and those tags use a composite primary key of both the PostID and the Tag.

When I run update-database I get:

Cannot define PRIMARY KEY constraint on nullable column in table 'PostTag'.

I've tried applying the [Required] attribute to both Post and PostID. I've tried placing the ForeignKey attribute on the other side of the FK relationship. I've tried applying the InverseProperty attribute to Post (which changes the error to just a vague NullReferenceException - this seems like a bug).

Was it helpful?

Solution

As it turns out if I place InverseProperty on the HashSet, EF can migrate the DB, but only if it's clean:

public class Post
{
    ...
    [InverseProperty("Post")]
    public HashSet<PostTag> Tags { get; set; }
}

If I migrate from a PostTag class that looks like this however:

public class PostTag
{
    public Post Post { get; set; }

    [Key]
    [ForeignKey("Post")]
    public int PostID { get; set; }

    [Key]
    [MaxLength(50)]
    public string Tag { get; set; }
}

I get the exception:

'FK_PostTag_Post_Post_ID' is not a constraint. Could not drop constraint. See previous errors.

Looks like it may be a bug with EF Code First in which it's allowing a Composite Key to be applied to these properties but not actually applying it in the database (the table that resulted from the above code had a single-column PK on Tag).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top