Entity Framework, one-to-many, several columns - entity-framework

If I have a main table, lets say orders, and a sub table of items and the items table has a fields for item number BUT it also has a nullable (optional) field for color that applied only to certain items. How would I update the items table, at the same time as the orders table, using Entity Framework?
Here is a code example of what I have so far. Two problems, I'm only entering one of my items and, from what my research indicates, I can't add another field to the items table?
foreach (Guid c in AllItems)
{ Items.OrderItemID = Guid.NewGuid();
ITemsOrderID = order.OrderID;
ITems.ItemID = c;
If (ItemID = ItemThatLetsYouChoseAColorID)
{
Items.ItemColorID = ColorID;
} else {
Items.ItemColorID = null;
}
}
context.Orders.AddObject(Orders);
context.Items.AddObject(Items);
context.SaveChanges();
My Orders table gets a record inserted, and the Items gets ONE record inserted. I'm missing something basic here, I'm afraid. BTW, this is Entity Framework 4.0, which. I believe, does not require the use of EntityKey.

You're adding an object to the Items collection only one time after the scope of your foreach.
Have you tested something like:
foreach (Guid c in AllItems)
{
var Item = new Item();
Item.OrderItemID = Guid.NewGuid();
Item.OrderID = order.OrderID;
Item.ItemID = c;
If (ItemID = ItemThatLetsYouChoseAColorID)
{
Item.ItemColorID = ColorID;
}
else
{
Item.ItemColorID = null;
}
context.Items.AddObject(Items);
}
context.Orders.AddObject(order);
context.SaveChanges();
And I'm not sure to understand what you mean by
I can't add another field to the items table
You should be more precise about what you actually expect. Insert a row, add a column in the table...? What is a "field"?

Here is the working code. I had the new Item outside the foreach item loop, so was overwriting the value. Also, I need to add each one to the context. I had a hard time with this, hope it helps someone else:
<-fill the order object->
foreach (Guid i in Items)
{
**Items item = new Items();**
item.ItemID = Guid.NewGuid();
item.OrderID = order.OrderID;
if (i == ItemWithColorGuid)
{
foreach (Guid c in Colors)
{
**Items color = new Items();**
color.ItemsID = Guid.NewGuid();
color.OrderID = order.orderID;
color.itemID = g;
color.colorID = c;
context.item.AddObject(color);
}
}
else
{
item.ItemID = i;
item.ColorID = null;
context.item.AddObject(item);
}
}
context.orders.AddObject(order);
context.SaveChanges();

Related

Saving changes if adding to context

EF Core 2.2.x
The question Im trying to answer is if I can limit my call of SaveChanges to only once or do I need it each time I add an entity, since in the next lower level I need to query the DbContext to see if the item exists.
Am trying to "merge" some data between two sets of similar tables. So in the process of adding records and drilling down the hierarchy, I have to first see if a record exists and if not, then add it.
/*
List<StagedOrder> sorders;
StagedOrder
Id
Number
InsertDate
Notes
StagedOrderLine
Id
ItemNo
Qty
StagedOrderKey
*/
foreach( StagedOrder s in sorders) {
// get order
Order o = (from a in ctx.Orders where a.number = s.Number select a).FirstOrDefault();
if(o == null) {
o = new Order() {
Number = s.Number,
InsertDate = DateTime.Now,
Notes = "imported order"
};
ctx.Orders.Add(o);
// ctx.SaveChanges() ???
}
// get lines for orders
OrderLines ol = (from a in ctx.DetailLines where a.OrderKey = o.Id select a).ToList();
if(ol == null) {
foreach(StagedOrderLine l in s.StagedOrderLines) {
ol = new DetailLine() {ItemNo = l.ItemNo, Qty = l.Qty, OrderKey = l.Id}
ctx.DetailLines.Add(ol);
ctx.SaveChanges();
}
}
}
// can I limit my call to savechanges only once here?
// ctx.SaveChanges();
Also, should I create a new DetailLine using an Order.Id or an entity reference, eg.
ol = new DetailLine() {ItemNo = l.ItemNo, Qty = l.Qty, Order = o}

How to log new records during SaveChanges

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.

EF6 update not actually updating the table record?

I'm having to write a app that effectively copies data from one databaseA.table to databaseB.table but there are a few fields in databaseB that aren't in databaseA.
I've come up with basic code below. The insert works and the update doesn't trow an error, however, the update doesn't actually update any records.
I've confirmed that the bcEmployee object in the update has the new values from databaseA like it should. The employee object is the record from databaseA.
Am I missing something to make this update?
BC_employee bcEmployee = new BC_employee();
bcEmployee.emp_id = employee.emp_id;
bcEmployee.emp_firstname = employee.emp_firstname;
bcEmployee.emp_lastname = employee.emp_lastname;
using (BCcontext ctx = new BCcontext())
{
var existBCemployee = ctx.employee.Find(employee.emp_id);
if (existBCemployee == null) //Insert
{
//Set default values that aren't in the original database
bcEmployee.emp_paystat = null;
bcEmployee.password = null;
bcEmployee.enroll_date = null;
ctx.employee.Add(bcEmployee);
}
else
{
ctx.Entry(existBCemployee).CurrentValues.SetValues(bcEmployee);
}
ctx.SaveChanges();
}

declare variable to store linq entity for conditional statements

I am trying to look up record using if I have the key then use Find if not use Where
private ApplicationDbContext db = new ApplicationDbContext();
public bool DeactivatePrice(int priceId = 0, string sponsorUserName = "")
{
var prices = db.BeveragePrices;
// if we have an id then find
if (priceId != 0)
{
prices = prices.Find(priceId);
}
else
{
prices = prices.Where(b => b.UserCreated == sponsorUserName);
}
if (prices != null)
{
// do something
}
return true;
I get the following error for
prices = prices.Find(priceId);
Cannot convert app.Model.BeveragePrices from system.data.entity.dbset
I am copying the pattern from this answer but something must be different.
Seems you forgot to put a predicate inside the Find function call. Also you need to do ToList on the collection. The second option is a lot more efficient. The first one gets the whole collection before selection.
Another note commented by #Alla is that the find returns a single element. So I assume another declaration had been made for 'price' in the first option I state down here.
price = prices.ToList.Find(b => b.PriceId == priceId);
Or
prices = prices.Select(b => b.PriceId == priceId);
I assume the field name is PriceId.

.Net Entity Framework SaveChanges is adding without add method

I'm new to the entity framework and I'm really confused about how savechanges works. There's probably a lot of code in my example which could be improved, but here's the problem I'm having.
The user enters a bunch of picks. I make sure the user hasn't already entered those picks.
Then I add the picks to the database.
var db = new myModel()
var predictionArray = ticker.Substring(1).Split(','); // Get rid of the initial comma.
var user = Membership.GetUser();
var userId = Convert.ToInt32(user.ProviderUserKey);
// Get the member with all his predictions for today.
var memberQuery = (from member in db.Members
where member.user_id == userId
select new
{
member,
predictions = from p in member.Predictions
where p.start_date == null
select p
}).First();
// Load all the company ids.
foreach (var prediction in memberQuery.predictions)
{
prediction.CompanyReference.Load();
}
var picks = from prediction in predictionArray
let data = prediction.Split(':')
let companyTicker = data[0]
where !(from i in memberQuery.predictions
select i.Company.ticker).Contains(companyTicker)
select new Prediction
{
Member = memberQuery.member,
Company = db.Companies.Where(c => c.ticker == companyTicker).First(),
is_up = data[1] == "up", // This turns up and down into true and false.
};
// Save the records to the database.
// HERE'S THE PART I DON'T UNDERSTAND.
// This saves the records, even though I don't have db.AddToPredictions(pick)
foreach (var pick in picks)
{
db.SaveChanges();
}
// This does not save records when the db.SaveChanges outside of a loop of picks.
db.SaveChanges();
foreach (var pick in picks)
{
}
// This saves records, but it will insert all the picks exactly once no matter how many picks you have.
//The fact you're skipping a pick makes no difference in what gets inserted.
var counter = 1;
foreach (var pick in picks)
{
if (counter == 2)
{
db.SaveChanges();
}
counter++;
}
I've tested and the SaveChanges doesn't even have to be in the loop.
The below code works, too.
foreach (var pick in picks)
{
break;
}
db.SaveChanges()
There's obviously something going on with the context I don't understand. I'm guessing I've somehow loaded my new picks as pending changes, but even if that's true I don't understand I have to loop over them to save changes.
Can someone explain this to me?
Here's updated working code based on Craig's responses:
1) Remove the Type then loop over the results and populate new objects.
var picks = (from prediction in predictionArray
let data = prediction.Split(':')
let companyTicker = data[0]
where !(from i in memberQuery.predictions
select i.Company.ticker).Contains(companyTicker)
select new //NO TYPE HERE
{
Member = memberQuery.member,
Company = db.Companies.Where(c => c.ticker == companyTicker).First(),
is_up = data[1] == "up", // This turns up and down into true and false.
}).ToList();
foreach (var prediction in picks)
{
if (includePrediction)
{
var p = new Prediction{
Member = prediction.Member,
Company = prediction.Company,
is_up = prediction.is_up
};
db.AddToPredictions(p);
}
}
2) Or if I don't want the predictions to be saved, I can detach the predictions.
foreach (var prediction in picks) {
if (excludePrediction)
{
db.Detach(prediction)
}
}
The reason is here:
select new Prediction
{
Member = memberQuery.member,
These lines will (once the IEnumerable is iterated; LINQ is lazy) :
Instantiate a new Prediction
Associate that Prediction with an existing Member, *which is attached to db.
Associating an instance of an entity with an attached entity automatically adds that entity to the context of the associated, attached entity.
So as soon as you start iterating over predictionArray, the code above executes and you have a new entity in your context.