EF Code First - Invalid column name - ef-code-first

Im getting an error "Invalid column name 'FeeLevel_LevelId' which makes absolutely no sense considering all properties are simple types and there is no FeeLevel nor a LevelId object in this object.
So my context is:
public partial class FeesDbContext : DisconnectedEntityContext
{
public DbSet<Currency> Currencies { get; set; }
public DbSet<FeeLevel> FeeLevels { get; set; }
public DbSet<FeeLevelDetail> FeeLevelDetails { get; set; }
public DbSet<FeeType> FeeTypes { get; set; }
public DbSet<MemberFeeDiscountLevel> MemberFeeDiscountLevels { get; set; }
public FeesDbContext()
: base("FeesDb") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new FeeLevelMap());
modelBuilder.Configurations.Add(new FeeLevelDetailMap());
modelBuilder.Configurations.Add(new FeeTypeMap());
modelBuilder.Configurations.Add(new CurrencyMap());
modelBuilder.Configurations.Add(new MemberFeeDiscountLevelMap());
}
public static void ApplyChanges<TEntity>(TEntity root)
where TEntity : class, IObjectWithState
{
using (var context = new FeesDbContext())
{
context.Set<TEntity>().Add(root);
foreach (var entry in context.ChangeTracker.Entries<IObjectWithState>())
{
IObjectWithState stateInfo = entry.Entity;
entry.State = ConvertState(stateInfo.State);
}
context.SaveChanges();
}
}
}
The POCO is:
public partial class MemberFeeDiscountLevel : AbstractState
{
public long MemberFeeDiscountLevelId { get; set; }
public System.Guid MemberId { get; set; }
public short MemberAsType { get; set; }
public long FeeDiscountLevelId { get; set; }
public System.DateTime FeeDiscountLevelAppliedDate { get; set; }
public Nullable<System.DateTime> FeeDiscountLevelExpiresDate { get; set; }
public Nullable<long> FallbackFeeDiscountLevelId { get; set; }
public System.Guid UserId { get; set; }
public System.DateTime LastModified { get; set; }
public MemberFeeDiscountLevel(ObjectState state) : base(state) { }
public MemberFeeDiscountLevel()
{
}
}
It's mapping is:
public class MemberFeeDiscountLevelMap : EntityTypeConfiguration<MemberFeeDiscountLevel>
{
public MemberFeeDiscountLevelMap()
{
// Primary Key
this.HasKey(t => t.MemberFeeDiscountLevelId);
this.Ignore(t => t.State);
// Properties
// Table & Column Mappings
this.ToTable("MemberFeeDiscountLevel");
this.Property(t => t.MemberFeeDiscountLevelId).HasColumnName("MemberFeeDiscountLevelId");
this.Property(t => t.MemberId).HasColumnName("MemberId");
this.Property(t => t.MemberAsType).HasColumnName("MemberAsType");
this.Property(t => t.FeeDiscountLevelId).HasColumnName("FeeDiscountLevelId");
this.Property(t => t.FeeDiscountLevelAppliedDate).HasColumnName("FeeDiscountLevelAppliedDate");
this.Property(t => t.FeeDiscountLevelExpiresDate).HasColumnName("FeeDiscountLevelExpiresDate");
this.Property(t => t.FallbackFeeDiscountLevelId).HasColumnName("FallbackFeeDiscountLevelId");
this.Property(t => t.UserId).HasColumnName("UserId");
this.Property(t => t.LastModified).HasColumnName("LastModified");
}
}
The database table is:
and it has not relationships. Yet EF is generating the following SQL:
exec sp_executesql N'INSERT [dbo].[MemberFeeDiscountLevel]([MemberId], [MemberAsType], [FeeDiscountLevelId], [FeeDiscountLevelAppliedDate], [FeeDiscountLevelExpiresDate], [FallbackFeeDiscountLevelId], [UserId], [LastModified], [FeeLevel_LevelId])
VALUES (#0, #1, #2, #3, #4, #5, #6, #7, #8, NULL)
SELECT [MemberFeeDiscountLevelId]
FROM [dbo].[MemberFeeDiscountLevel]
WHERE ##ROWCOUNT > 0 AND [MemberFeeDiscountLevelId] = scope_identity()',N'#0 uniqueidentifier,#1 smallint,#2 bigint,#3 datetime2(7),#4 datetime2(7),#5 bigint,#6 uniqueidentifier,#7 datetime2(7),#8 int',#0='DAF771D1-079F-4743-B5C7-FD0FA1C63E19',#1=0,#2=1012,#3='2014-01-24 12:05:36.0608347',#4='2014-02-01 00:00:00',#5=1018,#6='EEDF2C83-2123-4B1C-BF8D-BE2D2FA26D09',#7='2014-01-24 12:05:36.0608347'
go
UPDATE:
Creating a new Fees2DbContext stripping out the other DbSets "fixes" the problem.... but I dont know why... none of these classes / sets are related to the class in question.
public partial class Fees2DbContext : DisconnectedEntityContext
{
public DbSet<MemberFeeDiscountLevel> MemberFeeDiscountLevels { get; set; }
public Fees2DbContext()
: base("FeesDb") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new MemberFeeDiscountLevelMap());
}
public static void ApplyChanges<TEntity>(TEntity root)
where TEntity : class, IObjectWithState
{
using (var context = new Fees2DbContext())
{
context.Set<TEntity>().Add(root);
foreach (var entry in context.ChangeTracker.Entries<IObjectWithState>())
{
IObjectWithState stateInfo = entry.Entity;
entry.State = ConvertState(stateInfo.State);
}
context.SaveChanges();
}
}
}
UPDATE 2:
public partial class FeeLevel : AbstractState
{
public FeeLevel()
{
this.FeeLevelDetails = new List<FeeLevelDetail>();
this.MemberFeeDiscountLevels = new List<MemberFeeDiscountLevel>();
}
public long LevelId { get; set; }
public string LevelName { get; set; }
public int CurrencyId { get; set; }
public System.DateTime LastModified { get; set; }
public bool IsSystemOwned { get; set; }
public System.Guid UserId { get; set; }
public virtual Currency Currency { get; set; }
[ScriptIgnore]
public virtual ICollection<FeeLevelDetail> FeeLevelDetails { get; set; }
public virtual ICollection<MemberFeeDiscountLevel> MemberFeeDiscountLevels { get; set; }
}
public class FeeLevelMap : EntityTypeConfiguration<FeeLevel>
{
public FeeLevelMap()
{
// Primary Key
this.HasKey(t => t.LevelId);
this.Ignore(t => t.State);
// Properties
this.Property(t => t.LevelId);
// .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
this.Property(t => t.LevelName)
.IsRequired()
.HasMaxLength(50);
// Table & Column Mappings
this.ToTable("FeeLevel");
this.Property(t => t.LevelId).HasColumnName("LevelId");
this.Property(t => t.LevelName).HasColumnName("LevelName");
this.Property(t => t.CurrencyId).HasColumnName("CurrencyId");
this.Property(t => t.LastModified).HasColumnName("LastModified");
this.Property(t => t.UserId).HasColumnName("UserId");
// Relationships
this.HasRequired(t => t.Currency)
.WithMany(t => t.FeeLevels)
.HasForeignKey(d => d.CurrencyId);
}
}

FeeLevel.MemberFeeDiscountLevels is a navigation property and it introduces a one-to-many relationship between FeeLevel and MemberFeeDiscountLevel: A FeeLevel can have many MemberFeeDiscountLevels which means at the same time that a MemberFeeDiscountLevel has a single FeeLevel. Although you don't have a navigation and foreign key property in MemberFeeDiscountLevel the database must have a foreign key in the MemberFeeDiscountLevel table in order to model this relationship. EF assumes a default FK name as "related entity name+underscore+primary key name" = FeeLevel_LevelId. Because your database table doesn't have this column you get the exception.

Related

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Posts_Authors_AuthorId"

I successfully built migrations, and I am now trying to update the database with my models in Asp.net core but it keeps giving me this error
"The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Posts_Authors_AuthorId". The conflict occurred in database "MediumDb", table "dbo.Authors", column 'AuthorId'.
The statement has been terminated."
This is what the code in my Post class looks like
namespace Medium.Api.Entities
{
public class Post
{
public Guid Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int NoOfClaps { get; set; }
public DateTime CreatedDate { get; set; }
public IQueryable<Tag> Tags { get; set; }
public IQueryable<PostTag> PostTags { get; set; }
public string Image { get; set; }
// public string Video { get; set; }
public Author Author { get; set; }
public int AuthorId { get; set; }
while the code in my Author class says this
namespace Medium.Api.Entities
{
public class Author
{
public int AuthorId { get; set; }
public string Name { get; set; }
public IQueryable<Post> Posts { get; set; }
}
}
This is my DbContext configuration
{
public class MediumApiContext : DbContext
{
public MediumApiContext(DbContextOptions options)
: base(options)
{
// Database.EnsureCreated();
}
public DbSet<Post> Posts { get; set; }
public DbSet<Author> Authors { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<PostTag> PostTags { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Author>()
.HasKey(a => a.AuthorId);
modelBuilder.Entity<Author>()
.HasMany(a => a.Posts)
.WithOne(p => p.Author);
modelBuilder.Entity<Post>()
.ToTable("Posts");
modelBuilder.Entity<Post>()
.HasKey(p => p.Id);
modelBuilder.Entity<Post>()
.HasOne(p => p.Author)
.WithMany(a => a.Posts);
modelBuilder.Entity<Post>()
.Property(p => p.CreatedDate)
.IsRequired()
.HasColumnType("Date")
.HasDefaultValueSql("getutcdate()");
modelBuilder.Entity<Post>()
.Property(p => p.Title)
.IsRequired();
modelBuilder.Entity<Post>()
.Property(p => p.NoOfClaps)
.IsRequired();
modelBuilder.Entity<Post>()
.Property(p => p.Content)
.IsRequired();
I don't know where I seem to be getting it all wrong. Please
We Use FK for data integrity right now you have FOREIGN KEY with Author Table so :
"The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Posts_Authors_AuthorId". The conflict occurred in database "MediumDb", table "dbo.Authors", column 'AuthorId'. The statement has been terminated."
This means that when you create a Post, you must give an Author_ID that is on the Author table

How can i access related data and convert foreign keys into objects for displaying their properties

I have
class User {
...
...
ICollection<Transaction> transactionsUserMade;
}
and
class Transaction {
int ID;
int userThatSentMoneyID;
int userToWhomHeSentMoneyID;
}
I'm trying to make profile page where user can see all transactions he made and to whom. I managed to relate users and transaction but I'm getting integer values, as i should by using
await _context.Users
.Include(u => u.transactionsUserMade)
.AsNoTracking()
.FirstOrDefaultAsync(u => u.ID == userId);
How can i turn those ID's to actual objects of Users so i could get their usernames and display them on Razor Page.
Found one solution. I tweaked Transaction class by adding User userThatRecievedMoney property. And after getting transactions from specific user i manually set that property.
foreach(var transaction in _user.transactionsUserMade)
{
transaction.userThatRecievedMoney = _context.Users
.Where(u => u.ID == transaction.userToWhomHeSentMoneyID).FirstOrDefault();
}
You can use Navigation Property to help you with that as long as you can modify those entity models User and Transaction.
public class UserEntity
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public List<TransactionEntity> TransactionsAsSender { get; set; }
public List<TransactionEntity> TransactionsAsRecipient { get; set; }
}
public class TransactionEntity
{
public int Id { get; set; }
public double Amount { get; set; }
public string Note { get; set; }
// Foreign key to UserEntity
public int SenderId { get; set; }
public UserEntity Sender { get; set; }
// Foreign key to UserEntity
public int RecipientId { get; set; }
public UserEntity Recipient { get; set; }
}
Then you need to setup their relationships.
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<UserEntity>(b => {
b.HasKey(x => x.Id);
b.Property(x => x.Name).IsRequired();
b.Property(x => x.Email).IsRequired();
b.ToTable("User");
});
builder.Entity<TransactionEntity>(b => {
b.HasKey(x => x.Id);
b.Property(x => x.Amount).IsRequired();
// Configure relationships
b.HasOne(x => x.Sender)
.WithMany(u => u.TransactionsAsSender)
.HasForeignKey(x => x.SenderId);
b.HasOne(x => x.Recipient)
.WithMany(u => u.TransactionsAsRecipient)
.HasForeignKey(x => x.RecipientId);
b.ToTable("Transaction");
});
}
public DbSet<UserEntity> Users { get; set; }
public DbSet<TransactionEntity> Transactions { get; set; }
}
After their relationships are setup, you can easily query the related data via navigation properties.
For example, let's say you have view model called UserProfileViewModel and UserProfileTransactionViewModel to contain the information it needs for display purpose.
public class UserProfileViewModel
{
public int UserId { get; set; }
public string UserName { get; set; }
public string UserEmail { get; set; }
public IEnumerable<UserProfileTransactionViewModel> TransactionsAsSender { get; set; }
public IEnumerable<UserProfileTransactionViewModel> TransactionsAsRecipient { get; set }
}
public class UserProfileTransactionViewModel
{
public int TransactionId { get; set; }
public string Sender { get; set; }
public string Recipient { get; set; }
public string Amount { get; set; }
}
In the controller,
var user = _dbContext.Users
.AsNoTracking()
.Include(x => x.TransactionsAsSender)
.Include(x => x.TransactionsAsRecipient)
.SingleOrDefault(x => x.Id == userId);
if (user == null)
{
return NotFound();
}
var vm = new UserProfileViewModel
{
UserId = user.Id,
UserName = user.Name,
UserEmail = user.Email,
TransactionsAsSender = user.TransactionsAsSender
.Select(x => new UserProfileTransactionViewModel
{
TransactionId = x.Id,
Sender = x.Sender.Name,
Recipient = x.Recipient.Name,
Amount = x.Amount.ToString("c")
}),
TransactionsAsRecipient = user.TransactionsAsRecipient
.Select(x => new UserProfileTransactionViewModel
{
TransactionId = x.Id,
Sender = x.Sender.Name,
Recipient = x.Recipient.Name,
Amount = x.Amount.ToString("c")
})
};
return View(vm);
You could even have just a list of all transactions off UserProfileViewModel. You can combine TransactionsAsSender and TransactionsAsRecipient from UserEntity to fill the list.
Disclaim:
I wrote everything by hand and with my imagination :p

Entity Code First String FK values Uppercase or Lowercase

FK is linked to tbWarehouseUser 1 recording.
There are both lowercase and uppercase values in the tbWarehouseUser table.
How can I solve this problem ?
The classes are as follows;
private void Form1_Load(object sender, EventArgs e)
{
var model = new Model1();
var tbWarehouse = model.tbWarehouse.Where(c=> c.sWarehouse == "A1").FirstOrDefault();
var tbWarehouseUserList = tbWarehouse.tbWarehouseUser.ToList();
}
tbWarehouseUserList.Count record count 1.
1 record is coming. This problem causes sourced?
Recording picture
public partial class tbWarehouse
{
tbWarehouse()
{
tbWarehouseUser = new HashSet<tbWarehouseUser>();
}
[Key]
[StringLength(4)]
public string sWarehouse { get; set; }
public string WarehouseDescription { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<tbWarehouseUser> tbWarehouseUser { get; set; }
}
public partial class tbWarehouseUser
{
[Key]
[Column(Order = 0)]
[StringLength(4)]
public string sUserName { get; set; }
[Key]
[Column(Order = 1)]
[StringLength(4)]
public string sWarehouseName { get; set; }
public string sUserPass { get; set; }
public virtual tbWarehouse tbWarehouse { get; set; }
}
public partial class Model1 : DbContext
{
public Model1()
: base("name=Model1")
{
}
protected void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<tbWarehouse>()
.Property(e => e.sWarehouse)
.IsFixedLength()
.IsUnicode(false);
modelBuilder.Entity<tbWarehouse>()
.Property(e => e.WarehouseDescription)
.IsUnicode(false);
modelBuilder.Entity<tbWarehouse>()
.HasMany(e => e.tbWarehouseUser)
.WithRequired(e => e.tbWarehouse)
.HasForeignKey(e => e.sWarehouseName)
.WillCascadeOnDelete(false);
modelBuilder.Entity<tbWarehouseUser>()
.Property(e => e.sUserName)
.IsFixedLength()
.IsUnicode(false);
modelBuilder.Entity<tbWarehouseUser>()
.Property(e => e.sWarehouseName)
.IsFixedLength()
.IsUnicode(false);
modelBuilder.Entity<tbWarehouseUser>()
.Property(e => e.sUserPass)
.IsFixedLength()
.IsUnicode(false);
}
}

EF Code First: Migrations removing needed columns and adding unwanted ones

Note: there is a "better" iteration of this question here:
EF Code First migrations: Table Per Hierarchy Bug
I am trying to figure out the exact steps need to take an existing database and overlay entity framework code first with a Table Per Hierarchy structure. However no matter what I do, the end result migration is "wrong".
Here is the sample database, exact steps and output.
Existing database structure
CREATE TABLE [dbo].[Categories](
[Id] [int] IDENTITY(1,1) NOT NULL Primary Key,
[Name] [nvarchar](100) NOT NULL,
)
GO
CREATE TABLE [dbo].[A](
[Id] [int] IDENTITY(1,1) NOT NULL Primary Key,
[Discriminator] [nvarchar](20) NOT NULL,
[Description] [nvarchar](100) NOT NULL,
[CategoryId] [int] NULL
)GO
ALTER TABLE [dbo].[A]
WITH CHECK ADD CONSTRAINT [FK_dbo.A_dbo.Categories_CategoryId]
FOREIGN KEY([CategoryId])
REFERENCES [dbo].[Categories] ([Id])
GO
ALTER TABLE [dbo].[A]
CHECK CONSTRAINT [FK_dbo.A_dbo.Categories_CategoryId]
GO
"Reverse Engineer Code First" generates the following:
public partial class EntityContext : DbContext {
static EntityContext() {
Database.SetInitializer<EntityContext>(null);
}
public EntityContext()
: base("Name=Test47Context") {
}
public DbSet<A> A { get; set; }
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Configurations.Add(new AMap());
modelBuilder.Configurations.Add(new CategoryMap());
}
}
public partial class A {
public int Id { get; set; }
public string Discriminator { get; set; }
public string Description { get; set; }
public Nullable<int> CategoryId { get; set; }
public virtual Category Category { get; set; }
}
public partial class Category {
public Category() {
this.A = new List<A>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<A> A { get; set; }
}
public class AMap : EntityTypeConfiguration<A> {
public AMap() {
// Primary Key
this.HasKey(t => t.Id);
// Properties
this.Property(t => t.Discriminator)
.IsRequired()
.HasMaxLength(20);
this.Property(t => t.Description)
.IsRequired()
.HasMaxLength(100);
// Table & Column Mappings
this.ToTable("A");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.Discriminator).HasColumnName("Discriminator");
this.Property(t => t.Description).HasColumnName("Description");
this.Property(t => t.CategoryId).HasColumnName("CategoryId");
// Relationships
this.HasOptional(t => t.Category)
.WithMany(t => t.A)
.HasForeignKey(d => d.CategoryId);
}
}
public class CategoryMap : EntityTypeConfiguration<Category> {
public CategoryMap() {
// Primary Key
this.HasKey(t => t.Id);
// Properties
this.Property(t => t.Name)
.IsRequired()
.HasMaxLength(100);
// Table & Column Mappings
this.ToTable("Categories");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.Name).HasColumnName("Name");
}
}
Implement TPH, by
Adding Derived.cs inherits from A.cs
Moving Category and CategoryId properties from A.cs to Derived.cs
Remove Discriminator property from A.cs
In AMap.cs remove Discriminator, CategoryId and Category Foreign Key mapping.
Adding TPH mapping to OnModelCreating
public partial class EntityContext : DbContext {
static EntityContext() {
Database.SetInitializer<EntityContext>(null);
}
public EntityContext()
: base("Name=Test47Context") {
}
public DbSet<A> A { get; set; }
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Configurations.Add(new AMap());
modelBuilder.Configurations.Add(new CategoryMap());
modelBuilder.Entity<A>()
.Map<Derived>(x => x.Requires("Discriminator").HasValue("Derived"));
}
}
public partial class A {
public int Id { get; set; }
public string Description { get; set; }
}
public class Derived : A {
public Nullable<int> CategoryId { get; set; }
public virtual Category Category { get; set; }
}
public partial class Category {
public Category() {
this.A = new List<A>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<A> A { get; set; }
}
public class AMap : EntityTypeConfiguration<A> {
public AMap() {
// Primary Key
this.HasKey(t => t.Id);
this.Property(t => t.Description)
.IsRequired()
.HasMaxLength(100);
// Table & Column Mappings
this.ToTable("A");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.Description).HasColumnName("Description");
}
}
public class CategoryMap : EntityTypeConfiguration<Category> {
public CategoryMap() {
// Primary Key
this.HasKey(t => t.Id);
// Properties
this.Property(t => t.Name)
.IsRequired()
.HasMaxLength(100);
// Table & Column Mappings
this.ToTable("Categories");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.Name).HasColumnName("Name");
}
}
"Add-migration TPH" generates the following
public partial class TPH : DbMigration
{
public override void Up()
{
AddColumn("dbo.A", "Category_Id", c => c.Int());
AddForeignKey("dbo.A", "Category_Id", "dbo.Categories", "Id");
CreateIndex("dbo.A", "Category_Id");
DropColumn("dbo.A", "Discriminator");
}
public override void Down()
{
AddColumn("dbo.A", "Discriminator", c => c.String(nullable: false, maxLength: 20));
DropIndex("dbo.A", new[] { "Category_Id" });
DropForeignKey("dbo.A", "Category_Id", "dbo.Categories");
DropColumn("dbo.A", "Category_Id");
}
}
Why does it drop the Discriminator column instead of just altering it to nvarchar(128)?
Why doesn't just use the existing CategoryId column instead of adding Category_Id?

Code first, customizing the join table [duplicate]

I have this scenario:
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; }
public int Something { get; set; }
public string SomethingElse { get; set; }
}
How do I configure my association with fluent API? Or is there a better way to create the association table?
It's not possible to create a many-to-many relationship with a customized join table. In a many-to-many relationship EF manages the join table internally and hidden. It's a table without an Entity class in your model. To work with such a join table with additional properties you will have to create actually two one-to-many relationships. It could look like this:
public class Member
{
public int MemberID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<MemberComment> MemberComments { get; set; }
}
public class Comment
{
public int CommentID { get; set; }
public string Message { get; set; }
public virtual ICollection<MemberComment> MemberComments { get; set; }
}
public class MemberComment
{
[Key, Column(Order = 0)]
public int MemberID { get; set; }
[Key, Column(Order = 1)]
public int CommentID { get; set; }
public virtual Member Member { get; set; }
public virtual Comment Comment { get; set; }
public int Something { get; set; }
public string SomethingElse { get; set; }
}
If you now want to find all comments of members with LastName = "Smith" for example you can write a query like this:
var commentsOfMembers = context.Members
.Where(m => m.LastName == "Smith")
.SelectMany(m => m.MemberComments.Select(mc => mc.Comment))
.ToList();
... or ...
var commentsOfMembers = context.MemberComments
.Where(mc => mc.Member.LastName == "Smith")
.Select(mc => mc.Comment)
.ToList();
Or to create a list of members with name "Smith" (we assume there is more than one) along with their comments you can use a projection:
var membersWithComments = context.Members
.Where(m => m.LastName == "Smith")
.Select(m => new
{
Member = m,
Comments = m.MemberComments.Select(mc => mc.Comment)
})
.ToList();
If you want to find all comments of a member with MemberId = 1:
var commentsOfMember = context.MemberComments
.Where(mc => mc.MemberId == 1)
.Select(mc => mc.Comment)
.ToList();
Now you can also filter by the properties in your join table (which would not be possible in a many-to-many relationship), for example: Filter all comments of member 1 which have a 99 in property Something:
var filteredCommentsOfMember = context.MemberComments
.Where(mc => mc.MemberId == 1 && mc.Something == 99)
.Select(mc => mc.Comment)
.ToList();
Because of lazy loading things might become easier. If you have a loaded Member you should be able to get the comments without an explicit query:
var commentsOfMember = member.MemberComments.Select(mc => mc.Comment);
I guess that lazy loading will fetch the comments automatically behind the scenes.
Edit
Just for fun a few examples more how to add entities and relationships and how to delete them in this model:
1) Create one member and two comments of this member:
var member1 = new Member { FirstName = "Pete" };
var comment1 = new Comment { Message = "Good morning!" };
var comment2 = new Comment { Message = "Good evening!" };
var memberComment1 = new MemberComment { Member = member1, Comment = comment1,
Something = 101 };
var memberComment2 = new MemberComment { Member = member1, Comment = comment2,
Something = 102 };
context.MemberComments.Add(memberComment1); // will also add member1 and comment1
context.MemberComments.Add(memberComment2); // will also add comment2
context.SaveChanges();
2) Add a third comment of member1:
var member1 = context.Members.Where(m => m.FirstName == "Pete")
.SingleOrDefault();
if (member1 != null)
{
var comment3 = new Comment { Message = "Good night!" };
var memberComment3 = new MemberComment { Member = member1,
Comment = comment3,
Something = 103 };
context.MemberComments.Add(memberComment3); // will also add comment3
context.SaveChanges();
}
3) Create new member and relate it to the existing comment2:
var comment2 = context.Comments.Where(c => c.Message == "Good evening!")
.SingleOrDefault();
if (comment2 != null)
{
var member2 = new Member { FirstName = "Paul" };
var memberComment4 = new MemberComment { Member = member2,
Comment = comment2,
Something = 201 };
context.MemberComments.Add(memberComment4);
context.SaveChanges();
}
4) Create relationship between existing member2 and comment3:
var member2 = context.Members.Where(m => m.FirstName == "Paul")
.SingleOrDefault();
var comment3 = context.Comments.Where(c => c.Message == "Good night!")
.SingleOrDefault();
if (member2 != null && comment3 != null)
{
var memberComment5 = new MemberComment { Member = member2,
Comment = comment3,
Something = 202 };
context.MemberComments.Add(memberComment5);
context.SaveChanges();
}
5) Delete this relationship again:
var memberComment5 = context.MemberComments
.Where(mc => mc.Member.FirstName == "Paul"
&& mc.Comment.Message == "Good night!")
.SingleOrDefault();
if (memberComment5 != null)
{
context.MemberComments.Remove(memberComment5);
context.SaveChanges();
}
6) Delete member1 and all its relationships to the comments:
var member1 = context.Members.Where(m => m.FirstName == "Pete")
.SingleOrDefault();
if (member1 != null)
{
context.Members.Remove(member1);
context.SaveChanges();
}
This deletes the relationships in MemberComments too because the one-to-many relationships between Member and MemberComments and between Comment and MemberComments are setup with cascading delete by convention. And this is the case because MemberId and CommentId in MemberComment are detected as foreign key properties for the Member and Comment navigation properties and since the FK properties are of type non-nullable int the relationship is required which finally causes the cascading-delete-setup. Makes sense in this model, I think.
I'll just post the code to do this using the fluent API mapping.
public class User {
public int UserID { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public ICollection<UserEmail> UserEmails { get; set; }
}
public class Email {
public int EmailID { get; set; }
public string Address { get; set; }
public ICollection<UserEmail> UserEmails { get; set; }
}
public class UserEmail {
public int UserID { get; set; }
public int EmailID { get; set; }
public bool IsPrimary { get; set; }
}
On your DbContext derived class you could do this:
public class MyContext : DbContext {
protected override void OnModelCreating(DbModelBuilder builder) {
// Primary keys
builder.Entity<User>().HasKey(q => q.UserID);
builder.Entity<Email>().HasKey(q => q.EmailID);
builder.Entity<UserEmail>().HasKey(q =>
new {
q.UserID, q.EmailID
});
// Relationships
builder.Entity<UserEmail>()
.HasRequired(t => t.Email)
.WithMany(t => t.UserEmails)
.HasForeignKey(t => t.EmailID)
builder.Entity<UserEmail>()
.HasRequired(t => t.User)
.WithMany(t => t.UserEmails)
.HasForeignKey(t => t.UserID)
}
}
It has the same effect as the accepted answer, with a different approach, which is no better nor worse.
The code provided by this answer is right, but incomplete, I've tested it. There are missing properties in "UserEmail" class:
public UserTest UserTest { get; set; }
public EmailTest EmailTest { get; set; }
I post the code I've tested if someone is interested.
Regards
using System.Data.Entity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
#region example2
public class UserTest
{
public int UserTestID { get; set; }
public string UserTestname { get; set; }
public string Password { get; set; }
public ICollection<UserTestEmailTest> UserTestEmailTests { get; set; }
public static void DoSomeTest(ApplicationDbContext context)
{
for (int i = 0; i < 5; i++)
{
var user = context.UserTest.Add(new UserTest() { UserTestname = "Test" + i });
var address = context.EmailTest.Add(new EmailTest() { Address = "address#" + i });
}
context.SaveChanges();
foreach (var user in context.UserTest.Include(t => t.UserTestEmailTests))
{
foreach (var address in context.EmailTest)
{
user.UserTestEmailTests.Add(new UserTestEmailTest() { UserTest = user, EmailTest = address, n1 = user.UserTestID, n2 = address.EmailTestID });
}
}
context.SaveChanges();
}
}
public class EmailTest
{
public int EmailTestID { get; set; }
public string Address { get; set; }
public ICollection<UserTestEmailTest> UserTestEmailTests { get; set; }
}
public class UserTestEmailTest
{
public int UserTestID { get; set; }
public UserTest UserTest { get; set; }
public int EmailTestID { get; set; }
public EmailTest EmailTest { get; set; }
public int n1 { get; set; }
public int n2 { get; set; }
//Call this code from ApplicationDbContext.ConfigureMapping
//and add this lines as well:
//public System.Data.Entity.DbSet<yournamespace.UserTest> UserTest { get; set; }
//public System.Data.Entity.DbSet<yournamespace.EmailTest> EmailTest { get; set; }
internal static void RelateFluent(System.Data.Entity.DbModelBuilder builder)
{
// Primary keys
builder.Entity<UserTest>().HasKey(q => q.UserTestID);
builder.Entity<EmailTest>().HasKey(q => q.EmailTestID);
builder.Entity<UserTestEmailTest>().HasKey(q =>
new
{
q.UserTestID,
q.EmailTestID
});
// Relationships
builder.Entity<UserTestEmailTest>()
.HasRequired(t => t.EmailTest)
.WithMany(t => t.UserTestEmailTests)
.HasForeignKey(t => t.EmailTestID);
builder.Entity<UserTestEmailTest>()
.HasRequired(t => t.UserTest)
.WithMany(t => t.UserTestEmailTests)
.HasForeignKey(t => t.UserTestID);
}
}
#endregion
I want to propose a solution where both flavors of a many-to-many configuration can be achieved.
The "catch" is we need to create a view that targets the Join Table, since EF validates that a schema's table may be mapped at most once per EntitySet.
This answer adds to what's already been said in previous answers and doesn't override any of those approaches, it builds upon them.
The model:
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 virtual ICollection<MemberCommentView> MemberComments { get; set; }
}
public class Comment
{
public int CommentID { get; set; }
public string Message { get; set; }
public virtual ICollection<Member> Members { get; set; }
public virtual ICollection<MemberCommentView> MemberComments { get; set; }
}
public class MemberCommentView
{
public int MemberID { get; set; }
public int CommentID { get; set; }
public int Something { get; set; }
public string SomethingElse { get; set; }
public virtual Member Member { get; set; }
public virtual Comment Comment { get; set; }
}
The configuration:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
public class MemberConfiguration : EntityTypeConfiguration<Member>
{
public MemberConfiguration()
{
HasKey(x => x.MemberID);
Property(x => x.MemberID).HasColumnType("int").IsRequired();
Property(x => x.FirstName).HasColumnType("varchar(512)");
Property(x => x.LastName).HasColumnType("varchar(512)")
// configure many-to-many through internal EF EntitySet
HasMany(s => s.Comments)
.WithMany(c => c.Members)
.Map(cs =>
{
cs.ToTable("MemberComment");
cs.MapLeftKey("MemberID");
cs.MapRightKey("CommentID");
});
}
}
public class CommentConfiguration : EntityTypeConfiguration<Comment>
{
public CommentConfiguration()
{
HasKey(x => x.CommentID);
Property(x => x.CommentID).HasColumnType("int").IsRequired();
Property(x => x.Message).HasColumnType("varchar(max)");
}
}
public class MemberCommentViewConfiguration : EntityTypeConfiguration<MemberCommentView>
{
public MemberCommentViewConfiguration()
{
ToTable("MemberCommentView");
HasKey(x => new { x.MemberID, x.CommentID });
Property(x => x.MemberID).HasColumnType("int").IsRequired();
Property(x => x.CommentID).HasColumnType("int").IsRequired();
Property(x => x.Something).HasColumnType("int");
Property(x => x.SomethingElse).HasColumnType("varchar(max)");
// configure one-to-many targeting the Join Table view
// making all of its properties available
HasRequired(a => a.Member).WithMany(b => b.MemberComments);
HasRequired(a => a.Comment).WithMany(b => b.MemberComments);
}
}
The context:
using System.Data.Entity;
public class MyContext : DbContext
{
public DbSet<Member> Members { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<MemberCommentView> MemberComments { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new MemberConfiguration());
modelBuilder.Configurations.Add(new CommentConfiguration());
modelBuilder.Configurations.Add(new MemberCommentViewConfiguration());
OnModelCreatingPartial(modelBuilder);
}
}
From Saluma's (#Saluma) answer
If you now want to find all comments of members with LastName =
"Smith" for example you can write a query like this:
This still works...
var commentsOfMembers = context.Members
.Where(m => m.LastName == "Smith")
.SelectMany(m => m.MemberComments.Select(mc => mc.Comment))
.ToList();
...but could now also be...
var commentsOfMembers = context.Members
.Where(m => m.LastName == "Smith")
.SelectMany(m => m.Comments)
.ToList();
Or to create a list of members with the name "Smith" (we assume there is
more than one) along with their comments you can use a projection:
This still works...
var membersWithComments = context.Members
.Where(m => m.LastName == "Smith")
.Select(m => new
{
Member = m,
Comments = m.MemberComments.Select(mc => mc.Comment)
})
.ToList();
...but could now also be...
var membersWithComments = context.Members
.Where(m => m.LastName == "Smith")
.Select(m => new
{
Member = m,
m.Comments
})
.ToList();
If you want to remove a comment from a member
var comment = ... // assume comment from member John Smith
var member = ... // assume member John Smith
member.Comments.Remove(comment);
If you want to Include() a member's comments
var member = context.Members
.Where(m => m.FirstName == "John", m.LastName == "Smith")
.Include(m => m.Comments);
This all feels like syntactic sugar, however, it does get you a few perks if you're willing to go through the additional configuration. Either way, you seem to be able to get the best of both approaches.
I've come back here a couple times now, but it seems that EF Core has done a few updates in the past decade, so here's where I'm at currently with setting up many-to-many with custom join entity:
public class MemberModel
{
public int MemberId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<CommentModel> Comments { get; set; }
}
public class CommentModel
{
public int CommentId { get; set; }
public string Message { get; set; }
public ICollection<MemberModel> Members { get; set; }
}
public class MemberCommentModel
{
public int Something { get; set; }
public string SomethingElse { get; set; }
public int MembersId { get; set; }
[ForeignKey("MembersId")]
public MemberModel Member { get; set; }
public int CommentsId { get; set; }
[ForeignKey("CommentsId")]
public CommentModel Comment { get; set; }
}
Then in your OnModelCreating:
//Allows access directly from Comments or Members entities to the other
builder.Entity<MemberModel>()
.HasMany(x => x.Comments)
.WithMany(x => x.Members)
.UsingEntity<MemberCommentModel>();
//Defines the actual relationships for the middle table
builder.Entity<MemberCommentModel>()
.HasOne(x => x.Comment)
.WithOne()
.OnDelete(DeleteBehavior.NoAction);
builder.Entity<MemberCommentModel>()
.HasOne(x => x.Member)
.WithOne()
.OnDelete(DeleteBehavior.NoAction);
TLDR; (semi-related to an EF editor bug in EF6/VS2012U5) if you generate the model from DB and you cannot see the attributed m:m table: Delete the two related tables -> Save .edmx -> Generate/add from database -> Save.
For those who came here wondering how to get a many-to-many relationship with attribute columns to show in the EF .edmx file (as it would currently not show and be treated as a set of navigational properties), AND you generated these classes from your database table (or database-first in MS lingo, I believe.)
Delete the 2 tables in question (to take the OP example, Member and Comment) in your .edmx and add them again through 'Generate model from database'. (i.e. do not attempt to let Visual Studio update them - delete, save, add, save)
It will then create a 3rd table in line with what is suggested here.
This is relevant in cases where a pure many-to-many relationship is added at first, and the attributes are designed in the DB later.
This was not immediately clear from this thread/Googling. So just putting it out there as this is link #1 on Google looking for the issue but coming from the DB side first.
One way to solve this error is to put the ForeignKey attribute on top of the property you want as a foreign key and add the navigation property.
Note: In the ForeignKey attribute, between parentheses and double quotes, place the name of the class referred to in this way.

Resources