开发者

EF - Code First: Problem saving values in a many-to-many relationship

开发者 https://www.devze.com 2023-03-27 19:59 出处:网络
I\'m trying to add a tagging system to a webapplication build on MVC3 with EF Code First for data access. The base is pretty simple. I have Projects, Companies and People who can have 1 or more tags.

I'm trying to add a tagging system to a webapplication build on MVC3 with EF Code First for data access. The base is pretty simple. I have Projects, Companies and People who can have 1 or more tags. I do not want to save the tags for each entity alone, so the tag class has 3 ICollections: People, Companies and Projects. Each of the entities has an ICollection of tag. see the code below

public class Project 
{
    public int ID { get; set; }
    public virtual ICollection<Tag> Tags { get; set; }
}

public class Person
{
    public int ID { get; set; }
    public virtual ICollection<Tag> Tags { get; set; }
}

public class Company
{
    public int ID { get; set; }
    public virtual ICollection<Tag> Tags { get; set; }
}

public class Tag
{
    [Key]
    public int TagID { get; set; }
    public String Name { get; set; }

    public virtual ICollection<Project> Projects { get; set; }
    public virtual ICollection<Person> People { get; set; }
    public virtual ICollection<Company> Companies { get; set; }
}

In the context the mapping is set like this:

modelBuilder.Entity<Tag>()
    .HasMany(t => t.Projects)
    .WithMany(p => p.Tags)
    .Map(m =>
    {
        m.MapLeftKey("ID");
        m.MapRightKey("TagID");
        m.ToTable("TagProjects");
    });


modelBuilder.Entity<Tag>()
    .HasMany(t => t.People)
    .WithMany(p => p.Tags)
    .Map(m => 
    {
        m.MapLeftKey("ID");
        m.MapRightKey("TagID");
        m.ToTable("TagPeople");
    });

modelBuilder.Entity<Tag>()
    .HasMany(t => t.Companies)
    .WithMany(p => p.Tags)
    .Map(m =>
    {
        m.MapLeftKey("ID");
        m.MapRightKey("TagID");
        m.ToTable("TagCompanies");
    });

Now when I try to add a tag to a project like this:

public void AddTagToProject(int tagId, int projectId)
{
    ProjectRepository projectRepository = new ProjectRepository();
    Project pr开发者_如何学Gooject = projectRepository.GetProjectByID(projectId);
    project.Tags.Add(GetTagByID(tagId));

    Save();
}

there is no exception, but the project has no tags added to it either. Anyone have an idea where to look ?

public Tag GetTagByID(int tagId) 
{ 
    return db.Tags
        .Where(t => t.TagID == tagId)
        .First(); 
}

I've found the solution, the problem was that the project was not correctly updated and the values were never saved.


Have you made sure your database doesn't have any oddly named columns generated by EF 4.1? I had that happen once, and the FK column was called UserTrialLicense_UserTrialLicenseID. So anytime I tried to eager-load anything using .Include, it would not work.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号