Question

Excuse me for being a noob with EF when it comes to code first. My problem is I don't want to add foreign key properties to the model and according to MSDN this presents no problem using the fluent API, however I can not figure out the correct use for my current situation. It seems really simple:

public class Package
{
    public Package()
    {
        Users = new Collection<User>();
    }

    public Int32 Id {get; set;}
    public String Name {get; set;}
    public virtual User Creator {get; set;}

    public virtual ICollection<User> Users {get; set;}
}

public class User
{
    public Int32 Id {get; set;}
    public String Name {get; set;}
}

public class PackageContext : DbContext
{
    public DbSet<Package> Packages {get; set;}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Package>().HasRequired(p => p.Creator).WithMany();
        modelBuilder.Entity<Package>().HasMany(p => p.Users).WithRequired().Map(c => c.MapKey("PackageId"));

        base.OnModelCreating(modelBuilder);
    }
}

I've tried many differnt fluent combinations but nothing worked correctly. The most common exception I'm getting is this:

System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types.

Could someone please help me figure out the correct fluent calls I need to be making when creating the model?

Accepted Answer

u should use this :

public class Package
{
    public Int32 Id {get; set;}
    public String Name {get; set;}
    public Int32 UserId {get; set;}

    public virtual User Creator {get; set;}    
}

public class User
{
    public User()
    {
        Packages = new Collection<Package>();
     }

    public Int32 Id {get; set;}
    public String Name {get; set;}

    public virtual ICollection<Package> Packages {get; set;}
}

public class PackageContext : DbContext
{
    public DbSet<Package> Packages {get; set;}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Package>().HasRequired(current => current.Creator)
            .WithMany(c=>c.Packages)
            .HasForeignKey(c=>c.UserId)
            .WillCascadeOnDelete(false);

    base.OnModelCreating(modelBuilder);
    }
}



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why