I realize this has been answered more than once, here for example, but nothing seems to be working for me and I'm not sure why.
My database has Sites and Users. A User might own a Site, or he might work at a Site. He might own Sites A and C, but work on Site B. However, each site has only one worker and one owner. Therefore, I have created a join table structure with the following three tables: User, Site, and User_Site, and User_Site contains a column called role that can be either "worker" or "owner".
To simplify things, I have created two views, view_Worker and view_Owner. view_Owner, for example, is
SELECT User_Site.site_id, User.*
FROM User_Site
JOIN User ON User_Site.user_id = User.user_id
WHERE User_Site.role = "owner"
Therefore, each row in view_Owner contains all of the information on User and the site_id for which the User is joined as an "owner".
Now, I'm trying to build an API around this database using Entity Framework 6. I've gotten a number of errors trying a number of different things, so I'm not sure which errors to post here. I'll post my most recent error:
dbContext.cs
public DbSet<User> Users { get; set; }
public DbSet<Site> Sites { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Site>()
.HasOptional<User>(s => s.Owner)
.WithMany()
.Map(m =>
{
m.MapKey("site_id").ToTable("view_Owner");
});
}
user.cs
[Table("User")]
public class User
{
[Key, Column("user_id")]
public int ID { get; set; }
}
site.cs
[Table("Site")]
public class Site
{
[Key, Column("site_id")]
public int ID { get; set; }
public virtual User Owner { get; set; }
}
The error message I get with this configuration is
The specified table 'view_Owner' was not found in the model. Ensure that the table name has been correctly specified.
So, the next step is to try and add this table to the model. I change [Table("User")]
to [Table("view_Owner")]
and I get the following error message:
(66,6) : error 3021: Problem in mapping fragments starting at line 66:Each of the following columns in table User is mapped to multiple conceptual side properties: User.site_id is mapped to (66,6) : error 3025: Problem in mapping fragments starting at line 66:Must specify mapping for all key properties (User.user_id) of table User.
Clarification
Ideally, I'd like a way to simply tell EntityFramework to load the Owner property on Site from the view_Owner table by joining view_Owner.site_id to the Site.site_id primary key. But, since the Owner property is still of type User, it doesn't need a new definition.