[英]EF6 Code First many-to-many without collections
So I have the following model in EF: 因此,我在EF中具有以下模型:
public class User: IEntity
{
public Guid Id { get; protected set; }
public string Email { get; protected set; }
internal User()
{
}
public User(Guid id, string email)
{
Id = id;
Email = email;
}
}
public class Tenant : IEntity
{
public Guid Id { get; protected set; }
public string Name { get; protected set; }
internal Tenant() { }
public Tenant(Guid id, string name)
{
Id = id;
Name = name;
}
}
I would like to have a many-to-many relationship between these entities without having collections in them. 我想在这些实体之间建立多对多关系,而不必在其中包含集合。
I have tried creating a join entity like: 我试过创建一个连接实体,如:
public class TenantUser
{
public int Id { get; set; }
public virtual Tenant Tenant { get; set; }
public virtual User User { get; set; }
internal TenantUser ()
{
}
public TenantUser(Tenant tenant, User user )
{
this.Tenant = tenant;
this.User = user;
}
}
With the following setup: 使用以下设置:
modelBuilder.Entity<TenantUser>()
.HasRequired<Tenant>(m => m.Tenant)
.WithMany();
modelBuilder.Entity<TenantUser>()
.HasRequired<User>(m => m.User)
.WithMany();
When I save TenantUser objects, the database is populated with the correct foreign keys. 保存TenantUser对象时,将使用正确的外键填充数据库。 When I query the TenantUser DbSet for all rows, it returns all rows, but I'm only getting the Id value populated, Tenant and User are both null.
当我查询TenantUser DbSet中的所有行时,它返回所有行,但是我只填充了Id值,Tenant和User均为null。
I tried adding TenantId and UserId fields to TenantUser and then doing HasForeignKey for those fields, but it made no difference; 我尝试将TenantId和UserId字段添加到TenantUser,然后为这些字段执行HasForeignKey,但这没什么区别; TenantId and UserId were populated on query, but Tenant and User were still null.
在查询中填充了TenantId和UserId,但Tenant和User仍然为空。
I feel like I'm missing something simple here. 我觉得这里缺少一些简单的东西。 Any thoughts would be great :)
任何想法都会很棒:)
If you want many-to-many then remove the configuration: 如果要多对多,请删除配置:
modelBuilder.Entity<TenantUser>()
.HasRequired<Tenant>(m => m.Tenant)
.WithMany();
modelBuilder.Entity<TenantUser>()
.HasRequired<User>(m => m.User)
.WithMany();
Why? 为什么? Because EF use agreements:
由于EF使用协议:
public class User: IEntity
{
public Guid Id { get; protected set; }
}
public class Tenant : IEntity
{
public Guid Id { get; protected set; }
}
public class TenantUser
{
public int Id { get; set; }
public virtual Tenant Tenant { get; set; }
public virtual User User { get; set; }
}
This is fluent many-to-many. 这是多对多流利的。
When you make a query, use: 查询时,请使用:
public class UnitOfWork : DbContext
{
public IDbSet<User> Users { get; set; }
public IDbSet<Tenant> Tenants { get; set; }
public IDbSet<TenantUser> TenantUsers { get; set; }
}
context.TenantUsers.Include(e => e.Tenant).Include(e => e.User);
Then EF Include them in the mapping 然后EF将它们包括在映射中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.