简体   繁体   中英

Assign property value from another property value that is in a related table

I have a table called PRODUCT , in which the Price of a Product is stored. Because I know that the price of a product can change at any time, I have a table called ORDER , which holds the Quantity of the product that is being ordered by someone, and the TodaysPrice , which is the price that should be extracted from the column Price in the moment where the transaction is being done.

The problem is, I don't know how to extract a property's value and assign this value to another property in LightSwitch.


So far, what I've managed to think is to include this in the Order_Created() :

this.Order.SelectedItem.Price = this.Order.SelectedItem.Product.Price;

But the code above doesn't work, I get this exception:

NullReferenceException was unhandled by user code

I'm not sure if the is correct, any help would be much appreciated. I want to know how can I do this in LightSwitch 2011 with Visual Studio 2010.

Thanks so much in advance!

Your code is probably running when SelectedItem , or Product , does not currently have a value. You should always check for null before referencing any property of an entity.

Like this (notice how each entity is checked before referencing any properties of that entity:

if (this.Order != null) 
    && (this.Order.SelectedItem != null) 
    && (this.Order.SelectedItem.Product != null)
{
    this.Order.SelectedItem.Price = this.Order.SelectedItem.Product.Price;
}

The *Order_Created* method is not the right place to have this code, because at the point when the Order is created, you don't yet know which Product is going to be selected . The correct place to put this code is in the *Product_Changed* method, so that when the Product is selected (or changed), the Product 's current price then gets enetered in the Order .

Just on another note, unless you've simplified your tables for the example, I think you're missing a table. An Order will usually will have things like an associated Customer , a Date etc. It will also have a collection of OrderLines (or some similar name) It's the OrderLine that should have the product/qty/price details, not the Order itself.

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