简体   繁体   中英

Set a column value based on other column value on Entity Framework

I have a table contains 2 columns named Id ( IDENTITY(1,1)) and OriginalId

When we newly add an entity, OriginalId always equals to Id

To do that, I must write this stupid code

  MyClass obj = new MyClass()
  _repo.Add(obj);
  obj.OriginalId = obj.Id;
  _repo.Update(obj)

This one need to write to database 2 times . Is there any way to make it write one time only to have OriginalId = Id Regards,

if your obj.id is auto-increment, just try to get the latest id in _repo before adding your new obj to the repository. Do something like this:

MyClass obj = new MyClass();

var latestId = _repo.GetLatestId();
obj.OriginalId = ++latestId;

_repo.Add(obj);

However, If you don't want to access the repository two times, you need to change your table scheme. Your id should not be auto-increment and you need to generate the id by yourself or you can use Guid.NewGuid method to generate a unique id . In this case, try something like this:

MyClass obj = new MyClass();

obj.id = Guid.NewGuid();
obj.OriginalId = obj.id;

_repo.Add(obj);

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