我有这种情况:
public class Member
{
public int MemberID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
public class Comment
{
public int CommentID { get; set; }
public string Message { get; set; }
public virtual ICollection<Member> Members { get; set; }
}
public class MemberComment
{
public int MemberID { get; set; }
public int CommentID { get; set; } …Run Code Online (Sandbox Code Playgroud) 在这个问题:Ef Many To Many,一个关于如何手动指定链接表的答案.但我有一个稍微独特的情况(我肯定不是真的很独特).
我的两个表都有一个Id字段.EG:[dbo].[Account].[Id]和[dbo].[Person].[Id].我的Code-First中的每个表都有以下OnModelCreating:
modelBuilder.Entity<Account>.HasKey(x => x.Id);
modelBuilder.Entity<Person>.HasKey(x => x.Id);
Run Code Online (Sandbox Code Playgroud)
但我的[dbo].[AccountsToPersons]...桌子有EG:[AccountId]和[PersonId]
AccountsToPersons表不由代码中的类表示.
我显然已经有了一个现有的模型,但是我们使用EF Code-First Fluent API而不是从数据库更新模型.
那么如何更改此代码以使其与映射不同的ID列名称一起使用?
public DbSet<Person> Persons { get; set; }
public DbSet<Account> Accounts { get; set; }
. . .
modelBuilder.Entity<Account>()
.HasMany(a => a.Persons)
.WithMany()
.Map(x =>
{
x.MapLeftKey("AccountId"); // <-- Account.Id to AccountsToPersons.AccountId??
x.MapRightKey("PersonId"); // <-- Person.Id to AccountsToPersons.PersonId??
x.ToTable("AccountsToPersons");
});
Run Code Online (Sandbox Code Playgroud)
运行基本的Linq To EF Query时(from x in context.Accounts select x).ToList();,查询失败并显示以下错误:
我在使用FLuent API和EF Core理解和实现多对多的重复性方面遇到了麻烦.
我已经查看了这个问题并完全建立了我的关系但是我收到以下错误:
错误CS1061'CollectionNavigationBuilder'不包含'WithMany'的定义,并且没有扩展方法'WithMany'接受类型'CollectionNavigationBuilder'的第一个参数可以找到(你是否缺少using指令或程序集引用?)
这是我的意图.我有一个有很多工作的客户.我应该能够获得与该客户相关联的所有工作.EF应该在后台创建连接表...
这是我的课程:
public class Client : IEntityBase
{
public int Id { get; set; }
public int? JobId { get; set; }
public ICollection<Job> Jobs { get; set; }
}
public class Job : IEntityBase
{
public int Id { get; set; }
}
//my interface
public interface IEntityBase
{
int Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
编辑这是我试过的Fluent API,我在".withMany"上收到错误
modelBuilder.Entity<Client>()
.HasMany(p => p.Jobs)
.WithMany(p => p.clients)
.Map(m =>
{
m.MapLeftKey("ClientId");
m.MapRightKey("JobId");
m.ToTable("ClientJob"); …Run Code Online (Sandbox Code Playgroud)