how to Insert data from source to destination with no primary key & column names are invalid
Data.cs(source class ) no primary and foreign key relationship and column are same datatype but names are different between source and destination table
public class Data
{
public string Abc { get; set; }
public string cde { get; set; }
public string efg{ get; set; }
}
Data2.cs(destination class)no primary and foreign key relationship
public class data2
{
public string A_Abc { get; set; }
public string A_cde { get; set; }
public string A_efg{ get; set; }
}
source table
column name : abc,bcd,egf
destination table:
column name: A_abc,A_bcd,A_egf
error:-
'Data table requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'
after adding Hasnokey in Data2DBcontext.cs(destination.cs)
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity().HasNoKey();
}
again getting invalid column names error

Ali BenchaabanRank #925 · 2.2K reputationPosted Mar 25, 2023, 7:00 AM EDT
Hello Meghana M ,
To define Keyless Entities in EF, there are two ways : based in your example
1- Use data annotation
[Keyless]. Annotate a model with this attribute[Keyless] public class Data { public string Abc { get; set; } public string cde { get; set; } public string efg{ get; set; } }OR
2- use fluent API
.HasNoKeyto define the keyless entity// DbContext public class Data2DBcontext : DbContext { public Data2DBcontext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .HasNoKey(); } public DbSet Datas { get; set; } }BENCHAABAN Ali
Meghana MRank #8,429 · 222 reputationPosted Mar 25, 2023, 7:16 AM EDT
after using fluent API
.HasNoKeyto define the keyless entity issue is resolved but again getting another error invalid column namesource table
column name : abc,bcd,egf
destination table:
column name: A_abc,A_bcd,A_egf
Tuhin PaulRank #7 · 71.9K reputationPosted Mar 26, 2023, 5:39 AM EDT
To insert data from a source to a destination table in Entity Framework Core with different column names and no primary key, you can use a combination of LINQ and mapping to achieve this. Fetch the data from the source table and map it to the destination table.
var sourceData = _dbContext.Data.ToList(); var destinationData = sourceData.Select(s => new Data2 { A_Abc = s.Abc, A_cde = s.cde, A_efg = s.efg }).ToList();Tuhin PaulRank #7 · 71.9K reputationPosted Mar 26, 2023, 5:40 AM EDT
Once you have the data in the destinationData list, you can insert it into the destination table using the AddRange method of the DbContext class.
This will insert all the data from the destinationData list into the Data2 table.