SapientGuardian.EntityFrameworkCore.MySql
SapientGuardian.EntityFrameworkCore.MySql copied to clipboard
Unable save or read data with Many-to-Many relationship in MySql
hi, i was trying to use with blow sample code DbContext and usage code
public class Many2ManyDbContext : DbContext { private string _connectionString = string.Empty; public Many2ManyDbContext(string connectionString) { this._connectionString = connectionString; } public DbSet<Post> Posts { get; set; } public DbSet<Tag> Tags { get; set; } public DbSet<PostTag> PostTags { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//optionsBuilder.Usesq(@"Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
optionsBuilder.UseMySql(this._connectionString);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<PostTag>()
.HasKey(t => new { t.PostId, t.TagId });
modelBuilder.Entity<PostTag>()
.HasOne(pt => pt.Post)
.WithMany(p => p.PostTags)
.HasForeignKey(pt => pt.PostId);
modelBuilder.Entity<PostTag>()
.HasOne(pt => pt.Tag)
.WithMany(t => t.PostTags)
.HasForeignKey(pt => pt.TagId);
}
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public List<PostTag> PostTags { get; set; }
}
public class Tag
{
public string TagId { get; set; }
public List<PostTag> PostTags { get; set; }
}
public class PostTag
{
public int PostId { get; set; }
public Post Post { get; set; }
public string TagId { get; set; }
public Tag Tag { get; set; }
}
using (var context = new Many2ManyDbContext(@"Server=localhost;database=BlogPostMany2;uid=root;pwd=mysql2016;")) { context.Database.EnsureCreated();
foreach (var item in context.PostTags.Include(p => p.Post).Include(t => t.Tag))
{
Console.WriteLine($"Tag:\n\t TagId:{item.Tag.TagId}");
Console.WriteLine($"Post:\n\tTitle:{item.Post.Title} \t\tContent: {item.Post.Content}");
}
var tag = new Tag { TagId = Guid.NewGuid().ToString() };
var post = new Post { Title = "Intro to C#", Content = "Just testing" };
var postTage = new PostTag { Tag = tag, Post = post };
context.PostTags.Add(postTage);
context.SaveChanges();
foreach (var item in context.PostTags.Include(p => p.Post).Include(t => t.Tag))
{
Console.WriteLine($"Tag:\n\t TagId:{item.Tag.TagId}");
Console.WriteLine($"Post:\n\tTitle:{item.Post.Title} \t\tContent: {item.Post.Content}");
}
}
@vikasjain6 And the error? What is the result of this code for you?
It would also be worth trying this with EF Core 1.1 now as that has many improvements.