Insert Data Using Entity Framework Model

Insert data using Entity Framework model

It should be:

context.TableName.AddObject(TableEntityInstance);

Where:

  1. TableName: the name of the table in the database.
  2. TableEntityInstance: an instance of the table entity class.

If your table is Orders, then:

Order order = new Order();
context.Orders.AddObject(order);

For example:

 var id = Guid.NewGuid();

// insert
using (var db = new EfContext("name=EfSample"))
{
var customers = db.Set<Customer>();
customers.Add( new Customer { CustomerId = id, Name = "John Doe" } );

db.SaveChanges();
}

Here is an example:

public void UpdatePlayerScreen(byte[] imageBytes, string installationKey)
{
var player = (from p in this.ObjectContext.Players where p.InstallationKey == installationKey select p).FirstOrDefault();

var current = (from d in this.ObjectContext.Screenshots where d.PlayerID == player.ID select d).FirstOrDefault();

if (current != null)
{
current.Screen = imageBytes;
current.Refreshed = DateTime.Now;

this.ObjectContext.SaveChanges();
}
else
{
Screenshot screenshot = new Screenshot();

screenshot.ID = Guid.NewGuid();
screenshot.Interval = 1000;
screenshot.IsTurnedOn = true;
screenshot.PlayerID = player.ID;
screenshot.Refreshed = DateTime.Now;
screenshot.Screen = imageBytes;

this.ObjectContext.Screenshots.AddObject(screenshot);
this.ObjectContext.SaveChanges();
}
}

Entity Framework Core insert record into database

A bank is an entity that exists as stated a (singleton), a bank will not change and it's properties are it's own. A policy is issued by a bank, therefore, a policy should reference a bank via the banks Guid or ID property (foreign key), this will then create the parent -> child relationship which you desire. This is a ONE-TO-MANY relationship. I think you may want to either spend some more time learning about database relational design or draw these things out on paper before creating your entity classes.

EDIT: Igor has given you an option to stay the course and not change your entities, but I think you should take a good hard look at structuring your entities in a way that would mirror a database relational design. Just my opinion.

dotnet Entity Framework INSERT SELECT FROM other table

I did find a way to make one sql query to perform the lookup and execute the insert. I (only) managed to implement it using ExecuteSqlRaw.

string sqlText = "INSERT INTO \"Log\" (\"Timestamp\", \"Value\", \"Status\") " +
"SELECT {0}, {1}, COALESCE(\"Stat\".\"ID\", -1) " +
"FROM \"Status\" AS \"Stat\" " +
"RIGHT JOIN (SELECT 'xxx' as CONSTANT) AS \"Dummy\" " +
"ON \"Stat\".\"Name\" = {2}";
int rows = 0;
try
{
rows = context.Database.ExecuteSqlRaw(sqlText, timestamp, value, status);
if (rows != 1)
{
Console.WriteLine("Error writing status log to database: rows returned is {0}", rows);
}
}
catch (Exception ex)
{
Console.WriteLine("Error writing status log to database: {0}", ex.Message);
}

Although this works, I went for another solution. Since the Status table does not hold a large list, I load the table into a dictionary in memory and lookup the ID in there for every record that has to be added.

statusValues = context.Status.ToDictionary(kvp => kvp.Name, kvp => kvp.Id);

How to insert a record or multiple records using entity framework core using dbcontext (soap ui sends data to asp.net core via api call)

Try this code:

Fix your controller code:

using ... Data Access layer name space

....
......

var bdp=new bdpHmDao();

var miglistID = await bdp.AddBdpHmMigData(model);

Fix your action code

public async Task<int> AddBdpHmMigData(BDPHMMigModel model)
{
using (var context = new IpReservationContext())
{
var newcircuit = BdpMigrationList
{
CmNo = model.CmNo,
CmDate = model.CmDate,
Ipact = model.Ipact,
Site = model.Site,
Version = model.Version,
Circuit = model.Circuit,
Customer = model.Customer,
SourceDevice = model.SourceDevice,
SourceInterface = model.SourceInterface,
SourceInterfaceLag = model.SourceInterfaceLag,
DestDevice = model.DestDevice,
DestInterface = model.DestInterface,
DestInterfaceLag = model.DestInterfaceLag
};

context.Set<BdpMigrationList>().Add(newcircuit);
return await context.SaveChangesAsync();
}
}

How To Insert Data In FluentAPI Mapping Table

Edit: Since the question was changed, I'm writing up a more thorough answer. The answer to your question remains the same, however:

Now things are perfectly fine, but how do I insert in this AB Mapping
table?

You don't!

This is exactly the kind of thing that EF is good at. Instead of managing a link table yourself, now you just end up with the actual object you want. So, if you want to add a link between an A and B, all you do is add a B to the Bs collection on that A. You don't ever insert directly into the AB table, because who cares about that? That table is there so we can have relationships between different As and Bs, that's it. So, Entity Framework will create the table for it's own use, but not present it to you, because that's not how EF works: you work with your objects and let EF handle the database.

That's why when you try to define the table yourself, it creates two: it's already making a table called AB, but you're asking for another one. It can't have exactly the same name so it appends a '1' to the end of it. Since you've already used FluentAPI to define the apping, let EF worry about how to implement the mapping: all you need to care about is that you've now got a way to have an A with a set of Bs, or vice versa.

Since this still sounds confusing with names 'A' and 'B', below is the Program class for a console app that will illustrate this; all you need to do is start a fresh console app, replace the Program class with this one, install the entity framework package, and run enable-migrations -enableautomaticmigrations -force. I recommend you use this to add some objects and relate them, and then go have a look at your database: you will see the 'AB' table, with records that were added. This might help explain it better.

class Program
{
static bool quit = false;
static void Main(string[] args)
{
string s = "Please select an option:" +
"\n1: Insert an A" +
"\n2: Insert a B" +
"\n3: Add a B to an A" +
"\n4: Add an A to a B" +
"\n5: Print all As" +
"\n6: Print all Bs" +
"\n7: Print AB Table" +
"\nx: Quit.";

while (!quit)
{
Console.WriteLine();
Console.WriteLine(s);
var k = Console.ReadKey();
DoStuff(k);
}
}

private static void DoStuff(ConsoleKeyInfo i)
{
switch (i.Key)
{
case ConsoleKey.D1:
//add an A
AddA(GetName());
break;
case ConsoleKey.D2:
//add a B
AddB(GetName());
break;
case ConsoleKey.D3:
// link a B to an A
LinkB(GetBtoLink(),GetAtoLink());
break;
case ConsoleKey.D4:
//link an A to an B
LinkA(GetAtoLink(), GetBtoLink());
break;
case ConsoleKey.D5:
// print As
WriteA();
break;
case ConsoleKey.D6:
//print Bs
WriteB();
break;
case ConsoleKey.D7:
// print AB
WriteAB();
break;
case ConsoleKey.X:
quit = true;
break;
}
}

private static int GetAtoLink()
{
string x;
int z;

do
{
Console.Clear();
Console.WriteLine("Please enter the ID of the A you want to use and then press enter.");
WriteA();
x = Console.ReadLine();
} while (!int.TryParse(x, out z));

return z;
}

private static int GetBtoLink()
{
string x;
int z;

do
{
Console.Clear();
Console.WriteLine("Please enter the ID of the B you want to use and then press enter.");
WriteB();
x = Console.ReadLine();
} while (!int.TryParse(x, out z));

return z;
}

private static void WriteB()
{
Console.WriteLine("{0,10}{1,15}", "ID", "Name");
using (var db = new Context())
{
foreach (var a in db.Bs)
{
Console.WriteLine("{0,10}{1,15}", a.BID, a.Name);
}
}
}

private static void WriteA()
{
Console.WriteLine("{0,10}{1,15}", "ID", "Name");
using (var db = new Context())
{
foreach (var a in db.As)
{
Console.WriteLine("{0,10}{1,15}", a.AID, a.Name);
}
}
}

private static void WriteAB()
{
Console.WriteLine("{0,10}{1,10}", "AID", "BID");
using (var db = new Context())
{
// this is the only way we need to do this, because it's many to many,
// if an A is linked to a B, then that B is by definition linked to that A as well.
foreach (var a in db.As)
{
foreach (var b in a.Bs)
{
Console.WriteLine("{0,10}{1,10}", a.AID, b.BID);
}

}
}
}

private static void LinkB(int bToUse, int aToUse)
{
using (var db = new Context())
{
var a = db.As.First(x => x.AID == aToUse);
var b = db.Bs.First(y => y.BID == bToUse);
a.Bs.Add(b);
db.SaveChanges();
}
}

private static void LinkA(int aToUse, int bToUse)
{
using (var db = new Context())
{
var a = db.As.First(x => x.AID == aToUse);
var b = db.Bs.First(y => y.BID == bToUse);
b.As.Add(a);
db.SaveChanges();
}
}

private static string GetName()
{
Console.WriteLine("Please enter a name");
return Console.ReadLine();
}

private static void AddA(string input)
{
using (var db = new Context())
{
db.As.Add(new A {Name = input});
db.SaveChanges();
}
}

private static void AddB(string input)
{
using (var db = new Context())
{
db.Bs.Add(new B { Name = input });
db.SaveChanges();
}
}
}

public class A
{
public int AID { get; set; }
public string Name { get; set; }

public virtual ICollection<B> Bs { get; set; }
}

public class B
{
public int BID { get; set; }
public string Name { get; set; }

public virtual ICollection<A> As { get; set; }
}

public class Context : DbContext
{

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

modelBuilder.Entity<B>()
.HasMany(s => s.As)
.WithMany(c => c.Bs)
.Map(cs =>
{
cs.MapLeftKey("AID");
cs.MapRightKey("BID");
cs.ToTable("AB");
});

}

public DbSet<A> As { get; set; }
public DbSet<B> Bs { get; set; }
}

Old Answer: You've defined an ICollection<ApplicationUser> called Employees in Company, and mapped to it with FluentAPI. This creates a table called 'Employees' as expected. You don't have to create another class called Employees; as far as Entity Framework is concerned, you've already told it to create a table called Employees. This is why
I think the step you're missing is defining your DbSet<>.

Using your code, and running Add-Migration, this is the definition I get for the Employees table:

CreateTable(
"dbo.Employees",
c => new
{
UserID = c.Int(nullable: false),
CompanyID = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.UserID, t.CompanyID })
.ForeignKey("dbo.ApplicationUsers", t => t.UserID, cascadeDelete: true)
.ForeignKey("dbo.Companies", t => t.CompanyID, cascadeDelete: true)
.Index(t => t.UserID)
.Index(t => t.CompanyID);

Which seems to correlate with what you wanted.

To finish it off, add (if you haven't already) this to your ApplicationDbContext file:

public DbSet<ApplicationUser> Employees;
public DbSet<Company> Companies;

Then to add an employee, you create a new ApplicationUser and add it like

ApplicationUser user = new ApplicationUser();
// do whatever here to give it the right data

ApplicationDbContext ctx = new ApplicationDbContext();
ctx.Employees.Add(user);

The Employees table itself you shouldn't ever have to interact with.

EF Core : how to Insert data releated tables

Thanks to Pirate. I solved problem. I'm new in efcore but i was aware of many to many relationship unnecessary. I had done for many products with many categories but I changed my mind later. Maybe I can use it for next codes.

public override void Create(Product entity)
{
base.Create(entity);
using (var context = new FoodContext())
{
var product = context.Products
.Where(i=>i.ProductId==entity.ProductId)


.Include(i=>i.ProductCategories).FirstOrDefault();

product.ProductCategories.Add(new ProductCategory(){
ProductId=entity.ProductId,
CategoryId=(int)entity.CategoryId
});

context.SaveChanges();
}
}

Note: I don't know how true using double using-code-block

In EF Core 5, how can I insert an entity with a many to many relation by setting only the foreigns keys IDs, without querying first?

The issue will be due to the tracking, or lack of tracking on the Tags. Since you don't want to query the database, then you can opt to Attach tag instances that you can guarantee are legal tag rows. If you have a reasonable # of Tag IDs to use you could create and attach the full set to reference. Otherwise you could derive it from the data IDs coming in.

I.e. if we have 20 Tags to select from, ID 1-20:

for (int tagId = 1; tagId <= 20; tagId++)
{
var tag = new Tag { Id = tagId };
context.Tags.Attach(tag);
}

We don't need to track these tags separately in a list. Once associated with the DbContext we can use context.Tags, or to be extra cautious about reads, context.Tags.Local
then when populating your Posts:

var post = new Post { Text = "some text"});
post.Tags.Add(context.Tags.Local.Single(x => x.Id == 1));
post.Tags.Add(context.Tags.Local.Single(x => x.Id == 2));
posts.Add(post);
//...

context.Posts.AddRange(posts);

If you have a large # of tags and pass a structure in for the posts that nominate the Tag IDs you want to associate with each new post, then you can build a list from that:

var tags = postViewModels.SelectMany(x => x.TagIds)
.Distinct()
.Select(t => new Tag { Id == t)).ToList();

Such as the case where a provided set of post ViewModels contains a list of TagIds. We select all of the distinct Tag IDs, then build Tags to associate.

The caveat here is if the DbContext might already by tracking a Tag with any of the desired IDs. Calling Attach for a Tag that the DbContext might already have loaded will result in an exception. Whether you build a complete set of tags or build a set from the provided post, the solution should check the DbContext for any locally cached/tracked tags and only attach ones that aren't already tracked.

var tags = postViewModels.SelectMany(x => x.TagIds)
.Distinct()
.Select(t => new Tag { Id == t))
.ToList();
foreach(var tag in tags)
{
if (!context.Tags.Local.Any(x => x.TagId == tag.Id))
context.Tags.Attach(tag);
}

There may be a better way to build the Tags to attach to exclude existing tracked tags (such as using Except, though that requires an EqualityComparer) but we guard against attaching a Tag that is already tracked. From there we create the Posts and associate the desired tags as per the first example using context.Tags.Local. Every tag referenced in each post should have been attached or already tracked and available.

The remaining caveat here is that this assumes that the provided Tag actually exists in the database. We don't want to set the attached Tag's EntityState to anything like Added or Modified to avoid creating incomplete/invalid or replacing data in the Tags table.



Related Topics



Leave a reply



Submit