简体   繁体   中英

Insert into table without PK in Entity Framework Core

I'm currently using .NET Core 3.1, I want to make Integration some of my data into an existing application. This application is using SQL Server as the database at first I want to use SSIS to integrate my data into this application but I just know that they are using SQL Server Express so I can't use SSIS.

So I decided to create a hangfire job to get my data (multiple sources) and insert it into the existing application using EF Core. But now I just know that the table doesn't have PK since It already running for quite some time and is not my application I can't just add the pk to the table. When I try to Insert it using EF Core I got this error

System.InvalidOperationException: 'Unable to track an instance of type 'T1Item' because it does not have a primary key. Only entity types with primary keys may be tracked.'

Here is my code:

using (var scope = scopeFactory.CreateScope())
{
    var db1 = scope.ServiceProvider.GetRequiredService<db1Context>();
    var db2 = scope.ServiceProvider.GetRequiredService<db2Context>();

    var stagingTableConfig = db1 .KreTableFlagConfiguration.Where(x => x.TableName.ToLower() == "kre_productcategory").FirstOrDefault();

    if (stagingTableConfig != null)
    {
        var listProductCategory = db1.KreProductCategory.Where(x => x.Id > stagingTableConfig.LastataIndex).ToList();

        if (listProductCategory.Count > 0)
        {   
            long lastIndex = listProductCategory.Select(x => x.Id).Max();
            stagingTableConfig.LastataIndex = lastIndex;

            List<T1Item> listT1Items = new List<T1Item>();

            foreach (var pc in listProductCategory)
            {
                T1Item t1Item = new T1Item()
                            {
                                TiKd = pc.Category,
                                TiNm = pc.Name,
                                FlagApproval = 0,
                                FlagCleansing = 0,
                                TiKet = pc.Description
                            };

                listT1Items.Add(t1Item);
            }

            db2.T1Item.AddRange(listT1Items);
            db2.SaveChanges();

            db1.KreTableFlagConfiguration.Update(stagingTableConfig);
            db2.SaveChanges();
        }
    }
}

I wonder if there is a way I can insert it using ef core. Maybe there is another option to using ADO net to insert into a table that using PK. But if I can use EF core I prefer using EF Core.

Edit

modelBuilder.Entity<T1Item>(entity =>
            {
                entity.HasNoKey();

                entity.ToTable("T1_ITEM");

                entity.Property(e => e.FlagApproval)
                    .HasColumnName("FLAG_APPROVAL")
                    .HasColumnType("numeric(5, 0)");

                entity.Property(e => e.FlagCleansing)
                    .HasColumnName("FLAG_CLEANSING")
                    .HasColumnType("numeric(5, 0)");

                entity.Property(e => e.ItPk)
                    .HasColumnName("IT_PK")
                    .HasColumnType("numeric(10, 0)");

                entity.Property(e => e.TiKd)
                    .HasColumnName("TI_KD")
                    .HasMaxLength(5)
                    .IsUnicode(false)
                    .IsFixedLength();

                entity.Property(e => e.TiKet)
                    .HasColumnName("TI_KET")
                    .HasMaxLength(255)
                    .IsUnicode(false);

                entity.Property(e => e.TiNm)
                    .HasColumnName("TI_NM")
                    .HasMaxLength(255)
                    .IsUnicode(false);
            });

You can use Keyless attribute on youe model or use HasNoKey fluent api in ef core like this:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
    .Entity<BlogPostsCount>(
        eb =>
        {
            eb.HasNoKey();
            eb.Property(v => v.BlogName).HasColumnName("Name");
        });
}

Or for use attribute:

[Keyless]
public class BlogPostsCount
{
public string BlogName { get; set; }
public int PostCount { get; set; }
}

However, they are different from regular entity types in that they:

1- Cannot have a key defined.

2- Are never tracked for changes in the DbContext and therefore are never inserted, updated or deleted on the database.

3- Are never discovered by convention. Only support a subset of navigation mapping capabilities, specifically: They may never act as the principal end of a relationship.

4- They may not have navigations to owned entities They can only contain reference navigation properties pointing to regular entities.

5- Entities cannot contain navigation properties to keyless entity types.

6- May be mapped to a defining query. A defining query is a query declared in the model that acts as a data source for a keyless entity type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM