currently I'm Inserting like:
MyNamedEntities db = new MyNamedEntities();
MyTableEntity field = new MyTableEntity();
field.Name = "me";
db.MyTableEntity.AddObject(field);
db.SaveChanges()
But now I want to insert child elements and I need that field.Id part
MyOtherTableEntity field = new MyOtherTableEntity();
field.TableId = new MyTableEntity.First(x => x.Id.Equals( ... ));
How can I get the field.Id ?
If your table has defined the Id as an INT IDENTITY column, then you don't really have to do anything at all! :-)
In that case, just insert your entity and after the call to .SaveChanges(), your object should contain the new Id value:
MyTableEntity field = new MyTableEntity();
field.Name = "me";
db.MyTableEntity.AddObject(field);
db.SaveChanges();
int newID = field.Id;
You can also just add them to the parent by the association before or after the save changes
Something like this.
address a = new address();
a.city = "Detroit";
field.address.add(a);
db.SaveChanges();
Related
I want to log new and modified records. This code works just fine for Modified Records.
But with Added records, there is an issue. Since it is new to the Database, there is not yet a primary key for it. So there is no way to log which record was added.
However, if I try to log the records after the save, the EntityState is no longer Added. So I don't know what was added.
The only solution I have been able to come up with is to save a list of the new records, and then after the save, then Log the changes. But that seems like a workaround.
Is there some way to resolve this?
private List<Event> LogChanges(EntityEntry entityEntry, Enums.TableNames tableName)
{
List<Event> result = new List<Event>();
var databaseValues = entityEntry.GetDatabaseValues();
foreach (var property in entityEntry.CurrentValues.Properties.Where(a=> a.Name !="TenantId"))
{
string original = databaseValues[property]?.ToString();
string current = entityEntry.CurrentValues[property]?.ToString();
if(!object.Equals(original,current))
{
result.Add(
new Event()
{
AppUserId = this._appUserProvider.CurrentAppUserId,
EventDate = DateTimeOffset.UtcNow,
EventTypeId = (int)Enums.EventTypes.Modified,
TenantId = databaseValues.GetValue<int>("TenantId"),
RecordId = databaseValues.GetValue<int>("Id"),
ColumnName = property.Name,
OriginalValue = original,
NewValue = current,
TableId = (int)tableName
});
}
}
return result;
}
This library adds triggers to EntityFrameworkCore. Using the Triggers it provides is a much cleaner way to accomplish the above.
I have an object with several really large string properties. In addition, it has a simple timestamp property.
What I trying to achieve is to update only timestamp property without getting the whole huge object to the server.
Eventually, I would like to use EF and to do in the most performant way something equivalent to this:
update [...]
set [...] = [...]
where [...]
Using the following, you can update a single column:
var yourEntity = new YourEntity() { Id = id, DateProp = dateTime };
using (var db = new MyEfContextName())
{
db.YourEntities.Attach(yourEntity);
db.Entry(yourEntity).Property(x => x.DateProp).IsModified = true;
db.SaveChanges();
}
OK, I managed to handle this. The solution is the same as proposed by Seany84, with the only addition of disabling validation, in order to overcome issue with required fields. Basically, I had to add the following line just before 'SaveChanges():
db.Configuration.ValidateOnSaveEnabled = false;
So, the complete solution is:
var yourEntity = new YourEntity() { Id = id, DateProp = dateTime };
using (var db = new MyEfContextName())
{
db.YourEntities.Attach(yourEntity);
db.Entry(yourEntity).Property(x => x.DateProp).IsModified = true;
db.Configuration.ValidateOnSaveEnabled = false;
db.SaveChanges();
}
Here's the situation. I create 1 object (a product) and then save it through my db context. I then load that product from the database and put them in another object(download) and save that object. EF then creates another db entry for the original product loaded. So now I have two of the same product in the db. Is this working as intended? I thought EF kept track of objects loaded from the database to prevent stuff like this.
Ok here's some random code with one product if you really want it.
product product1 = new product{blah blah blah};
context.Products.add(product1);
context.savechanges();
var prod1 = context.Products.Where(x => x.Id == 1).FirstOrDefault();
user = new User { new Download {product = (product)prod1}};
context.Users.add(user);
context.save(user);
Here's an example:
var prod = context.Products.SingleOrDefault(p => p.Id == 1);
User user = context.Users.Create();
user.Product = prod;
context.Users.Add(user);
context.SaveChanges();
Or more easily...
User user = context.Users.Create();
user.ProductId = productId;
context.Users.Add(user);
context.SaveChanges();
I have an entity with two fk's. I've been trying to insert a record to the database without success. This are the approaches I've used:
valuePaymentBetToAdd.BetType = db.BetTypes.First(betType => betType.Id == valuePaymentBetToAdd.BetType.Id);
valuePaymentBetToAdd.Lottery = db.Lotteries.First(lotto => lotto.Id == valuePaymentBetToAdd.Lottery.Id);
In this case the second object gets assigned but when calling the SaveChanges method I get an error saying that the properties of the Lottery object were null.
valuePaymentBetToAdd.BetTypeReference.EntityKey = new EntityKey(db.DefaultContainerName + ".BetType", "Id", valuePaymentBetToAdd.BetType.Id);
valuePaymentBetToAdd.LotteryReference.EntityKey = new EntityKey(db.DefaultContainerName + ".Lottery", "Id", valuePaymentBetToAdd.Lottery.Id);
In this case I get another weird error. When the object is being added to the collection.
The object could not be added or attached because its EntityReference has an EntityKey property value that does not match the EntityKey for this object.
Am I missing something in this case?
Try setting the EntityReference like this:
valuePaymentBetToAdd.BetTypeReference.EntityKey = b.BetTypes.First(betType => betType.Id == valuePaymentBetToAdd.BetType.Id).EntityKey;
It works for me
How about creating a stub object for BetType and Lottery where you set only the Id property, and then attach those to their respective EntitySets, and then setting these objects on you Bet object, and save - something like:
Lottery lottery = new Lottery() { Id = valuePaymentBetToAdd.Lottery.Id };
BetType betType = new BetType() { Id = valuePaymentBetToAdd.BetType.Id };
MyContext.AttachTo("Lottery", lottery);
MyContext.AttachTo("BetType", betType);
valuePaymentBetToAdd.Lottery = lottery;
valuePaymentBetToAdd.BetType = betType;
MyContext.AddToBet(valuePaymentBetToAdd);
MyContext.SaveChanges();
I am using the ADO entity framework for the first time and am not sure of the best way of inserting db recored that contain foreign keys.
this is the code that i am using, I would appreciate any comments and suggestion on this.
using (KnowledgeShareEntities entities = new KnowledgeShareEntities())
{
Questions question = new Questions();
question.que_title = questionTitle;
question.que_question_text = questionText;
question.que_number_of_views = 0;
question.que_is_anonymous = isAnonymous;
question.que_last_activity_datetime = DateTime.Now;
question.que_timestamp = DateTime.Now;
question.CategoriesReference.Value = Categories.CreateCategories(categoryId);
question.UsersReference.Value = Users.CreateUsers(userId);
entities.AddToQuestions(question);
entities.SaveChanges();
return question.que_id;
}
You should use something like
question.UsersReference.EntityKey = new EntityKey("MyEntities.Users",
"ID", userId);
You don't have to have User object to set up foreign key, just use ID.