How to link to an existing post

Pass on me, this is my first question :)

I've been working with linqToSql for about a month now and there is only one thing that bothers me ...

Suppose I have an Entity called "Customer" and another one called CustomerType, Customer as a reference to CustomerType.

When inserting a customer, I need to set the CustumerType, I have a customerTypeID value that I want to set, so I do this:

if(c.CustomerTypeReference == null)
{
   c.CustomerTypeReference = new System.Data.Objects.DataClasses.EntityReference<CustomerType>
}


c.CustomerTypeReference.EntityKey = new System.Data.EntityKey("DataContext.CustomerType", "id", value);

      

It works, but it seems complicated to me. Is there any other way to do this?

Please note that I do not want to get a CustomerType object from the database, this example is simple, but I am working with objects that contain about 100 properties.

+1


source to share


1 answer


Are you using DBML Designer or are you manually coding entity classes? If you are working with a Designer, I would expect that since your table has a customerTypeID column, Customer

there will be a property named in your class customerTypeID

. All you really need to do is set the value of this property to the id value

  Customer c = new Customer();
  c.customerTypeID = value;

      



This should work fine, as long as you don't want to access the related objects themselves (i.e. you're going to store that particular object, not use it right away). If you need to access related objects - say, to access their properties - you will need to retrieve the values ​​from the database. I have to look at the code generated by the constructor, but I think that property settings on id-value columns do not update entity references, whereas object reference setters update id-value fields.

+1


source







All Articles