Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework: creating standalone entity

Good day, stackoverflow.
My question is: when the entity from DataContextModel is instantiated somewhere in the code, does it already have references to the database record? Or can it be used as common class ? For example:

public void SomeMethod()
{
   var FirstEntity = new DBEntity(); //DBEntity is some entity from the database
   var SecondEntity = new DBEntity();
   var ThirdEntity = new DBEntity();
   DbSet<DBEntity>.Add(SecondEntity);
   DbSet<DBEntity>.Add(ThirdEntity);
   DbContext.SaveChanges();
}

So, will FirstEntity be affected somehow, or it will be removed, when the SomeMethod exits?
Thanks in advance.

like image 742
Artyom Neustroev Avatar asked Feb 28 '26 00:02

Artyom Neustroev


1 Answers

It's just a plain class if outside the context.

But be careful, suppose this FirstEntity is referenced inside another object, as in:

var FirstEntity = new DBEntity(); 
var SecondEntity = new DBEntity();
var ThirdEntity = new DBEntity();
DbSet<DBEntity>.Add(SecondEntity);
DbSet<DBEntity>.Add(ThirdEntity);
SecondEntity.Sibling = FirstEntity;

When you save changes, if Sibling in the example is a foreign key reference, it will automatically add FirstEntity to the database.

Another example to be clear:

var Computer = new ComputerEntity();
var Motherboard = new MotherboardEntity();
Computer.Motherboard = Motherboard;
DbSet<ComputerEntity>.Add(Computer);
DbContext.SaveChanges();

This will save both Computer and Motherboard to the DB.

like image 183
Conrad Clark Avatar answered Mar 01 '26 13:03

Conrad Clark