EFCore data seeding missing data insertion? - c#

I have two related classes as follows:
public class Student
{
public long Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public long FavoriteCourseId { get; set; }
}
public class Course
{
public long Id { get; set; }
public string Name { get; set; }
}
There is one to one relationship between the two. Student has a foreign key which references the Course via the FavoriteCourseId.
My fluent mappings are as follows:
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.Entity<Student>(entity => {
entity.ToTable("Student").HasKey(k => k.Id);
entity.Property(p => p.Id).HasColumnName("StudentID");
entity.Property(p => p.Name).IsRequired();
entity.Property(p => p.Email).IsRequired();
entity.Property(p => p.FavoriteCourseId).IsRequired();
});
modelBuilder.Entity<Course>(entity => {
entity.ToTable("Course").HasKey(k => k.Id);
entity.Property(p => p.Id).HasColumnName("CourseID");
entity.Property(p => p.Name).IsRequired();
});
modelBuilder.Entity<Student>()
.HasOne(typeof(Course))
.WithOne()
.HasForeignKey("Student", "FavoriteCourseId")
.HasConstraintName("FK_Student_Course");
modelBuilder.Entity<Course>().HasData(
new Course { Id = 1, Name = "Calculus" },
new Course { Id = 2, Name = "Chemistry" },
new Course { Id = 3, Name = "Literature" },
new Course { Id = 4, Name = "Trigonometry" },
new Course { Id = 5, Name = "Microeconomics" });
modelBuilder.Entity<Student>().HasData(
new Student { Id = 1, Name = "Alice", Email = "alice#gmail.com", FavoriteCourseId = 2 },
new Student { Id = 2, Name = "Bob", Email = "bob#outlook.com", FavoriteCourseId = 2 });
}
Here, I am seeding two Students - Alice and Bob. However, when I create the init migration then the migration seeds only Bob and ignores Alice.
migrationBuilder.InsertData(
table: "Student",
columns: new[] { "StudentID", "Email", "FavoriteCourseId", "Name" },
values: new object[] { 2L, "bob#outlook.com", 2L, "Bob" });
Why is the data row for Alice being ignored? I also noticed that the data row only gets ignored when FavoriteCourseId is same for both Alice and Bob. If I change the FavoriteCourseId to different values for both rows then Alice gets inserted.

It seeds only one student because according your model the same course can only have one student. Change the model to this:
public class Student
{
[Key]
public long Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public long FavoriteCourseId { get; set; }
[ForeignKey(nameof(FavoriteCourseId ))]
[InverseProperty("FavoriteCourses")]
public virtual Course FavoriteCourse { get; set; }
}
public class Course
{
[Key]
public long Id { get; set; }
public string Name { get; set; }
[InverseProperty(nameof(Student.FavoriteCourse))]
public virtual ICollection<Student> Students{ get; set; }
}
and the dbcontext:
modelBuilder.Entity<Student>(entity =>
{
entity.HasOne(d => d.FavoriteCourse)
.WithMany(p => p.Courses)
.HasForeignKey(d => d.FavoriteCourseId)
.OnDelete(DeleteBehavior.ClientSetNull);
}
modelBuilder.Entity<Course>().HasData(
new Course { Id = 1, Name = "Calculus" },
new Course { Id = 2, Name = "Chemistry" },
new Course { Id = 3, Name = "Literature" },
new Course { Id = 4, Name = "Trigonometry" },
new Course { Id = 5, Name = "Microeconomics" });
modelBuilder.Entity<Student>().HasData(
new Student { Id = 1, Name = "Alice", Email = "alice#gmail.com", FavoriteCourseId = 2 },
new Student { Id = 2, Name = "Bob", Email = "bob#outlook.com", FavoriteCourseId = 2 });

Related

Seeding a value object. Best way to do that. .NET 6 with EF Core

I have an entity Product and a ValueObject Money.
public class Product
{
public Product() { }
[Key]
public int Id { get; set; }
public string Name { get; set; }
public Money Price { get; set; }
}
public class Money : BaseValueObject
{
public Money(string currency, decimal amount)
{
if (string.IsNullOrEmpty(currency))
throw new ArgumentNullException(nameof(currency));
this.Currency = currency;
this.Amount = amount;
}
public string Currency { get; private set; }
public decimal Amount { get; private set; }
protected override IEnumerable<object?> GetEqualityComponents()
{
yield return Currency;
yield return Amount;
}
}
I set up a table configuration in this way:
public class ProductEntityTypeConfiguration : IEntityTypeConfiguration<Product>
{
public void Configure(EntityTypeBuilder<Product> builder)
{
builder.ToTable("Products");
builder.HasKey(product => product.Id);
builder.Property(product => product.Name)
.HasColumnName("Name");
builder.OwnsOne(product => product.Price,
navigationBuilder =>
{
navigationBuilder.Property(money => money.Amount)
.HasColumnName("Price");
navigationBuilder.Property(money => money.Currency)
.HasColumnName("Currency");
});
}
}
public class ProductContext : DbContext
{
public ProductContext(DbContextOptions<ProductContext> options) : base(options) { }
public DbSet<Product> Products { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfiguration(new ProductEntityTypeConfiguration());
// seeding
modelBuilder.Entity<Product>(p =>
{
p.HasData(
new Product { Id = 1, Name = "cola" },
new Product { Id = 2, Name = "chips" },
new Product { Id = 3, Name = "candy" }
);
p.OwnsOne(p => p.Price).HasData(
new Money("EUR", 100),
new Money("EUR", 050),
new Money("EUR", 065)
);
});
}
Since Money is a valueObject, it has no keys. I would expect with this configuration to store instead of 1 price field, 2 fields: one named "Price" and another "Currency", in the same Product table.
The configuration runs correctly but as the "seeding" executes I get:
System.InvalidOperationException: 'The seed entity for entity type 'Money' cannot be added because no value was provided for the required property 'ProductId'.'
Don't understand why it's asking for the ProductId. So what is the correct way to seed a ValueObject ?
I'm using .NET 6 and EF Core 6.
For owned entity types for tracking needs a primary key is created as a shadow property for the owned type. The value of the key of an instance of the owned type will be the same as the value of the key of the owner instance.
You can specify value for it to seed the data using anonymous object:
modelBuilder.Entity<Product>(p =>
{
p.HasData(
new Product { Id = 1, Name = "cola" },
new Product { Id = 2, Name = "chips" },
new Product { Id = 3, Name = "candy" }
);
p.OwnsOne(pr => pr.Price)
.HasData(
new { ProductId = 1, Currency = "EUR", Amount = 100m },
new { ProductId = 2, Currency = "EUR", Amount = 050m },
new { ProductId = 3, Currency = "EUR", Amount = 065m }
);
});
As an alternative you could make a static class with following methods:
public class ProductEntityTypeConfiguration : IEntityTypeConfiguration<Product>
{
public void Configure(EntityTypeBuilder<Product> builder)
{
// ...
builder.OwnsOne(product => product.Price,
navigationBuilder =>
{
// ...
DataSeeder.Seed(navigationBuilder)
});
DataSeeder.Seed(builder);
}
private class DataSeeder
{
private static readonly List<Product> Products = new()
{
new Product { Name = "cola", Price = { Currency = "EUR", Amount = 100m } },
new Product { Name = "chips", Price = { Currency = "EUR", Amount = 100m } },
new Product { Name = "candy", Price = { Currency = "EUR", Amount = 100m } }
}
public static void Seed(EntityTypeBuilder<Product> builder)
{
builder.HasData(Products.Select((p, i) => new
{
ProductId = i + 1,
p.Name,
}));
}
public static void Seed(OwnedNavigationBuilder<Product, Money> builder)
{
builder.HasData(Products.Select((p, i) => new
{
ProductId = i + 1,
p.Price.Currency,
p.Price.Amount,
}));
}
}
}
This seems more readable for me and you don't have to specify ids explicitly.

Strange Entity Framework behavior

I have 2 models:
public class Office
{
[Key] public int OfficeId { get; set; }
public string Brand { get; set; }
public string Type { get; set; }
[NotMapped] public IRepository<CarItem> CarsDataBase { get; set; }
public virtual ICollection<CarItem> Cars { get; set; }
public Office(string brand, string type)
{
Type = type;
Cars = new List<CarItem>();
Brand = brand;
}
}
and
public class CarItem
{
public CarItem() { } //for serialization
public CarItem(string brand, string model, uint price, uint stockBalance)
{
Brand = brand;
Model = model;
Price = price;
StockBalance = stockBalance;
}
[Key] public int ItemId { get; set; }
public string Brand { get; set; }
public string Model { get; set; }
public uint Price { get; set; }
public uint StockBalance { get; set; }
public int? OfficeId { get; set; }
public Office Office { get; set; }
}
and DataBase Context
public class EFDataBaseContext : DbContext
{
public DbSet<Office> Offices => Set<Office>();
public DbSet<CarItem> CarItems => Set<CarItem>();
public EFDataBaseContext()
{
Database.EnsureCreated();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=carstoredb;Trusted_Connection=True;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Office>().HasData
(
new Office("Audi", "SQL")
{
OfficeId = 1,
},
new Office("Scoda", "SQL")
{
OfficeId = 2,
}
);
modelBuilder.Entity<CarItem>(entity =>
{
entity.HasOne(item => item.Office).WithMany(office => office.Cars).HasForeignKey(item => item.OfficeId).OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<SparePart>(entity =>
{
entity.HasOne(item => item.Office).WithMany(office => office.Parts).HasForeignKey(item => item.OfficeId).OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<CarItem>().HasData
(
new CarItem { OfficeId = 1, ItemId = 1, Brand = "Audi", Model = "A228", Price = 4, StockBalance = 14 },
new CarItem { OfficeId = 1, ItemId = 2, Brand = "Audi", Model = "Super", Price = 44, StockBalance = 5 },
new CarItem { OfficeId = 2, ItemId = 3, Brand = "Scoda", Model = "Logan", Price = 47, StockBalance = 9 },
new CarItem { OfficeId = 2, ItemId = 4, Brand = "Scoda", Model = "Spider", Price = 78, StockBalance = 3 }
);
}
Manually I added an office called BSU.
And in main function I write this:
using (EFDataBaseContext db = new EFDataBaseContext())
{
Office office = mainOffice.Dealerships.FirstOrDefault(of => of.Brand == "BSU");
CarItem carItem = new CarItem(office.Brand, "BSss", 2222, 4);
office.CarsDataBase ??= new EFDataBase(office);
office.CarsDataBase.Create(carItem);
}
Adding a new CarItem to the BSU somehow magically creates a new office named BSU in my database every time a new CarItem is added to the BSU.
using (EFDataBaseContext db = new EFDataBaseContext())
{
Office office = mainOffice.Dealerships.FirstOrDefault(of => of.Brand == "Audi");
CarItem carItem = new CarItem(office.Brand, "AuuuU", 2222, 4);
office.CarsDataBase ??= new EFDataBase(office);
office.CarsDataBase.Create(carItem);
}
Adding a new CarItem to an Audi, on the other hand, does absolutely nothing. No new cars with the Audi brand appear in the database, and nothing at all.
Seems like you're over complicating things
Adding a new Car to an existing Office should perhaps looks like:
var ctx = new EFDatabaseContext();
var off = ctx.Offices.FirstOrDefault(o => o.Type == "Main" and o.Brand == "Audi");
off.Cars.Add(new CarItem(off.Brand, "AuuuU", 2222, 4));
ctx.SaveChanges();
Find the office, add a car, save the changes

Convert flat db row data to nested typed objects linq

I'm getting the results of a sql outer join as flat results in an IEnumerable, and would like to convert them to nested typed objects in linq. From something like this:
[{id: 1, industryId: 1}, {id:1, industryId: 2}, {id:2, industryId: 1} etc..]
to something like this:
list of Company [{id: 1, list of Industry{industryId: 1, 2}, {id: 2, list of Industry{industryId: 1}}]
I'm currently trying a solution with GroupBy:
Companies = flatDbRows
.GroupBy(
row => row.CompanyId,
(key, value) => new CompanyModel
{
CompanyId = value.First().CompanyId,
CompanyName = value.First().CompanyName,
Industries = value
.GroupBy(
row => new { row.IndustryId, row.Industry },
(k, v) => new IndustryModel() { IndustryId = k.IndustryId, Name = k.Industry }
)
.Where(x => x.IndustryId != 0)
.ToList(),
}).ToList();
}
but it doesn't feel great, especially with all the value.First() I'm using to get the values that only belong to each grouped company. Is there something more appropriate? Group join sounded more like what I wanted, but I'm having trouble understanding how to apply it to a single list. I'm open to using query syntax instead of the lambdas if that's easier.
I'm trying to go from this model (where company-related info will be duplicated for each outer joined industry result):
public class CompanyFlatDbRowsModel
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public int IndustryId{ get; set; }
public string Industry { get; set; }
}
to this:
public class CompanyModel
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public IEnumerable<IndustryModel> Industries { get; set; }
}
// FULL edit after providing your models
public class TestClass
{
public class CompanyModel
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public List<IndustryModel> Industires { get; set; }
}
public class IndustryModel
{
public int IndustryId { get; set; }
public string IndustryName { get; set; }
}
public class CompanyFlatDbRowsModel
{
public CompanyFlatDbRowsModel()
{
}
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public int IndustryId { get; set; }
public string Industry { get; set; }
}
[Fact]
public void Test()
{
var data = new List<CompanyFlatDbRowsModel>
{
new CompanyFlatDbRowsModel
{
CompanyId = 1,
CompanyName = "Company 1",
IndustryId = 1,
Industry = "Industry 1"
},
new CompanyFlatDbRowsModel
{
CompanyId = 1,
CompanyName = "Company 1",
IndustryId = 2,
Industry = "Industry 2"
},
new CompanyFlatDbRowsModel
{
CompanyId = 2,
CompanyName = "Company 2",
IndustryId = 3,
Industry = "Industry 3"
},
new CompanyFlatDbRowsModel
{
CompanyId = 2,
CompanyName = "Company 2",
IndustryId = 4,
Industry = "Industry 4"
},
};
var result = data.GroupBy(x => x.CompanyId)
.Select(x => new CompanyModel()
{
CompanyId = x.Key,
CompanyName = x.First().CompanyName,
Industires = x.Select(y=> new IndustryModel
{
IndustryName = y.Industry,
IndustryId = y.IndustryId
}).ToList()
}).ToList();
foreach (var item in result)
{
var text = $"Company id : {item.CompanyId}, industries : {string.Join(',',item.Industires.Select(x=>$"(name: {x.IndustryName}, id: {x.IndustryId})"))}";
Debug.WriteLine(text);
}
}
}
output:
Company id : 1, industries : (name: Industry 1, id: 1),(name: Industry 2, id: 2)
Company id : 2, industries : (name: Industry 3, id: 3),(name: Industry 4, id: 4)
edit:
alternatively you can do as below, however the "first" thing still occurs somewhere, I have tried also the GroupJoin but it doesn't really help in that case.
var otherResult = data.Select(x =>
new CompanyModel
{
CompanyId = x.CompanyId,
CompanyName = x.CompanyName,
Industires = data
.Where(y => y.CompanyId == x.CompanyId)
.Select(y => new IndustryModel
{
IndustryId = y.IndustryId,
IndustryName = y.Industry
}).ToList()
})
.GroupBy(y => y.CompanyId)
.Select(x => x.First())
.ToList();
edit:
one more approach without using "first"
var anotherResult = data.GroupBy(x => x.CompanyId)
.Select(x =>
{
var companyModel = new CompanyModel()
{
CompanyId = x.Key
};
companyModel.Industires = x.Select(y =>
{
companyModel.CompanyName = y.CompanyName; // assignign here occurs multiple times however with the same value
return new IndustryModel
{
IndustryId = y.IndustryId,
IndustryName = y.Industry
};
}).ToList();
return companyModel;
}).ToList();

Entity Framework Seed method not running

I'm having some trouble getting the Seed method of EF to run. I've run update-database in the PMC - but no effect on the DB. Here's the method:
public class PhilosopherInitialiser : System.Data.Entity.DropCreateDatabaseIfModelChanges<PhilosopherContext>
{
protected override void Seed(PhilosopherContext context)
{
var philosophers = new List<Philosopher>{
new Philosopher {
FirstName = "Bertrand",
LastName = "Russell",
DateOfBirth = DateTime.Parse("1872-05-18"),
DateOfDeath = DateTime.Parse("1970-02-02"),
IsAlive = false,
NationalityID = 1,
AreaID = 7,
Description = "Here's some text about Bertrand Russell"
},
new Philosopher {
FirstName = "Immanuel",
LastName = "Kant",
DateOfBirth = DateTime.Parse("1724-04-22"),
DateOfDeath = DateTime.Parse("1804-02-12"),
IsAlive = false,
NationalityID = 3,
AreaID = 1,
Description = "Here's some text about Immanuel Kant"
},
new Philosopher {
FirstName = "John",
LastName = "Rawls",
DateOfBirth = DateTime.Parse("1921-02-21"),
DateOfDeath = DateTime.Parse("2002-11-24"),
IsAlive = false,
NationalityID = 9,
AreaID = 3,
Description = "Here's some text about John Rawls"
}
};
philosophers.ForEach(p => context.Philosophers.Add(p));
context.SaveChanges();
var nationalities = new List<Nationality>
{
new Nationality { Name = "English" },
new Nationality { Name = "Scotish" },
new Nationality { Name = "German" },
new Nationality { Name = "French" },
new Nationality { Name = "Greek" },
new Nationality { Name = "Italian" },
new Nationality { Name = "Spanish" },
new Nationality { Name = "Russian" },
new Nationality { Name = "American" }
};
nationalities.ForEach(n => context.Nationalities.Add(n));
context.SaveChanges();
var areas = new List<Area>{
new Area { Name = "Metaphysics" },
new Area { Name = "Existentialism" },
new Area { Name = "Political philosophy" },
new Area { Name = "Philosophy of the mind" },
new Area { Name = "Aesthetics" },
new Area { Name = "Social philosophy" },
new Area { Name = "Logic" },
new Area { Name = "Moral philosophy" },
new Area { Name = "Epistemology" }
};
areas.ForEach(a => context.Areas.Add(a));
context.SaveChanges();
var books = new List<Book>
{
new Book {
Title = "The impact of science on society",
PhilosopherID = 1,
AreaID = 6
},
new Book {
Title = "The analysis of mind",
PhilosopherID = 1,
AreaID = 4
},
new Book {
Title = "Marriage and morals",
PhilosopherID = 1,
AreaID = 8
},
new Book{
Title = "Critique of pure reason",
PhilosopherID = 2,
AreaID = 9
},
new Book{
Title = "The metaphysics of morals",
PhilosopherID = 2,
AreaID = 8
},
new Book{
Title = "A theory of justice",
PhilosopherID = 3,
AreaID = 3
}
};
books.ForEach(b => context.Books.Add(b));
context.SaveChanges();
}
}
}
And here's my PhilosopherContext class:
public class PhilosopherContext : DbContext
{
public PhilosopherContext() : base("PhilosopherContext")
{
}
public DbSet<Philosopher> Philosophers { get; set; }
public DbSet<Area> Areas { get; set; }
public DbSet<Nationality> Nationalities { get; set; }
public DbSet<Book> Books { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Book>()
.HasRequired(p => p.Philosopher)
.WithMany()
.HasForeignKey(p => p.PhilosopherID)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Philosopher>()
.Property(p => p.DateOfBirth)
.HasColumnType("datetime2");
modelBuilder.Entity<Philosopher>()
.Property(p => p.DateOfDeath)
.HasColumnType("datetime2");
}
}
}
Inside the Web.Config file I'm using initialising the DB here:
<contexts>
<context type="PhilosophersLibrary.DAL.PhilosopherContext, PhilosophersLibrary">
<databaseInitializer type="PhilosophersLibrary.DAL.PhilosopherInitialiser, PhilosophersLibrary" />
</context>
</contexts>
Does anyone have any suggestions? I feel that the method might not be called.
UPDATE
I seem to be making progress. The Areas and Nationalities tables are being seeded with the data. But I have to comment out the Philosophers data and the Books data. Is there something wrong with my data model?
public class Book
{
public int BookID { get; set; }
public string Title { get; set; }
[Display(Name = "Philosopher")]
public int PhilosopherID { get; set; }
[Display(Name = "Area")]
public int AreaID { get; set; }
public virtual Philosopher Philosopher { get; set; }
public virtual Area Area { get; set; }
}
public class Philosopher
{
// <className>ID pattern causes property to be primary key
public int PhilosopherID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[Display(Name = "Date of birth")]
public DateTime DateOfBirth { get; set; }
[Display(Name = "Date of death")]
public DateTime DateOfDeath { get; set; }
public Boolean IsAlive { get; set; }
public string Description { get; set; }
// Foreign keys have corresponding navigation properties
// <NavigationProperty>ID naming convention cause EF to identify foreign keys
public int NationalityID { get; set; }
public int AreaID { get; set; }
// Navigation properties - defined as virtual to use LazyLoading
// Nationality and Area have a 1 to 1 relationship with philosopher
// Books has a 1 to many relationship with philosopher
public virtual Nationality Nationality { get; set; }
public virtual Area Area { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
Try to use this:
CreateDatabaseIfNotExists<PhilosopherContext>
instead of this:
DropCreateDatabaseIfModelChanges<PhilosopherContext>
Also I would add:
public PhilosopherContext() : base("PhilosopherContext")
{
Database.SetInitializer<PhilosopherContext>(new CreateDatabaseIfNotExists<PhilosopherContext>());
}

Best approach to insert on many to many tables using Identity columns on ServiceStack ORMLite

Yesterday I found this great ORM and would like to perform some testings on more complex stuff than the samples provided on github.
This is the model I'm using
class BaseClass
{
[AutoIncrement]
public int Id { get; set; }
[StringLength(200)]
public string Name { get; set; }
}
[Alias("artist")]
class Artist : BaseClass
{
}
[Alias("genre")]
class Genre : BaseClass
{
}
[Alias("artistgenre")]
class ArtistGenre
{
[PrimaryKey]
public int Id { get; set; }
[Alias("idgenre")]
[References(typeof(Genre))]
public int IdGenre { get; set; }
[Alias("idartist")]
[References(typeof(Artist))]
public int IdArtist { get; set; }
}
And this is what I'm trying to achieve (although it doesn't work since the Identity values are unknown when inserting into artistgenre table).
if (dbConn.TableExists("artistgenre"))
dbConn.DropTable<ArtistGenre>();
if (dbConn.TableExists("artist"))
dbConn.DropTable<Artist>();
if (dbConn.TableExists("genre"))
dbConn.DropTable<Genre>();
dbConn.CreateTables(false, typeof(Artist), typeof(Genre), typeof(ArtistGenre));
var genres = new List<Genre>();
genres.Add(new Genre() { Name = "Rock" });
genres.Add(new Genre() { Name = "Pop" });
genres.Add(new Genre() { Name = "Jazz" });
genres.Add(new Genre() { Name = "Classic" });
genres.Add(new Genre() { Name = "Bossanova" });
var artists = new List<Artist>();
artists.Add(new Artist() { Name = "Rush" });
artists.Add(new Artist() { Name = "Queen" });
artists.Add(new Artist() { Name = "Pat Metheny" });
var ag = new List<ArtistGenre>();
var a = artists.FirstOrDefault(c => c.Name == "Rush");
var g = genres.FirstOrDefault(c => c.Name == "Rock");
ag.Add(new ArtistGenre() { IdArtist = a.Id, IdGenre = g.Id });
dbConn.SaveAll<Artist>(artists);
dbConn.SaveAll<Genre>(genres);
dbConn.SaveAll<ArtistGenre>(ag);
Is there a simple solution other than adding each row and obtaining its Identity values?
Thanks.
OrmLite doesn't currently populate the model with the auto-incrementing id atm. The way you obtain the autoincrement Id is to use db.GetLastInsertId() after each insert, e.g:
artists.ForEach(artist => {
db.Insert(artist);
artist.Id = db.GetLastInsertId();
});
I recommend wrapping this in an extension method to make this nicer to work with.

Categories

Resources