Saving Data to Relational Database (Entity Framework)

Posted by sheefy on Stack Overflow See other posts from Stack Overflow or by sheefy
Published on 2010-02-19T09:41:24Z Indexed on 2012/12/19 23:03 UTC
Read the original article Hit count: 158

Filed under:
|

I'm having a little bit of trouble saving data to a database. Basically, I have a main table that has associations to other tables (Example Below).

Tbl_Listing

  • ID
  • UserID - Associated to ID in User Table
  • CategoryID - Associated to ID in Category Table
  • LevelID - Associated to ID in Level Table.
  • Name
  • Address

Normally, it's easy for me to add data to the DB (using Entity Framework). However, I'm not sure how to add data to the fields with associations. The numerous ID fields just need to hold an int value that corresponds with the ID in the associated table.

For example; when I try to access the column in the following manner I get a "Object reference not set to an instance of an object." error.

Listing NewListing = new Listing();
NewListing.Tbl_User.ID = 1;
NewListing.Tbl_Category.ID = 2;
...

DBEntities.AddToListingSet(NewListing);
DBEntities.SaveChanges();

I am using NewListing.Tbl_User.ID instead of NewListing.UserID because the UserID field is not available through intellisense.

If I try and create an object for each related field I get a "The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects." error.

With this method, I am trying to add the object without the .ID shown above - example NewListing.User = UserObject.

I know this should be simple as I just want to reference the ID from the associated table in the main Listing's table. Any help would be greatly appreciated.

Thanks in advance,

-S

© Stack Overflow or respective owner

Related posts about database

Related posts about entity-framework