CSharp · Console
// @nuget: EntityFramework
// @nuget: EntityFramework.SqlServerCompact
// @nuget: Microsoft.SqlServer.Compact
// @nuget: Z.EntityFramework.Extensions
using System;
using System.Data.Entity;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
public class Program
{
public static void Main()
{
// Custom configuration specific for .NET Fiddle
Z.EntityFramework.Extensions.EntityFrameworkManager.UseFiddleSqlCompact(System.Data.Entity.SqlServerCompact.SqlCeProviderServices.Instance, System.Data.SqlServerCe.SqlCeProviderFactory.Instance);
using (var context = new BookStore())
{
Category category1 = new Category()
{
CategoryName = "category 1",
};
Category category2= new Category()
{
CategoryName = "category 2",
};
Book book1 = new Book()
{
Title = "MyBook 1",
Categories = new List<Category>()
{
category1,
category2
}
};
Book book2 = new Book()
{
Title = "MyBook 2",
Categories = new List<Category>()
{
category1
}
};
context.Books.Add(book1);
context.Books.Add(book2);
context.SaveChanges();
var categories = context.Categories.ToList();
var books = context.Books.ToList();
FiddleHelper.WriteTable(books);
FiddleHelper.WriteTable(categories);
}
}
public class BookStore : DbContext
{
public BookStore() : base(@"Data Source=ZZZ_Projects.sdf")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Book>()
.HasMany(b => b.Categories)
.WithMany(c => c.Books)
.Map(cs =>
{
cs.MapLeftKey("BookId");
cs.MapRightKey("CategoryId");
cs.ToTable("BookCategories");
});
}
public DbSet<Category> Categories { get; set; }
public DbSet<Book> Books { get; set; }
}
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public virtual ICollection<Category> Categories { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
}