开发者

Saving Data to Relational Database (Entity Framework)

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


In general, with Entity Framework you don't use the ID:s of foreign keys, instead you use references. Instead of setting the ID, you set the property of the associated table.

In your case, it would be something like this:

Listing newListing = new Listing();
newListing.Tbl_User = DBEntities.Users.Single(u=>u.ID == 1);
newListing.Tbl_Category = DBEntities.Categories.Single(c=>c.ID == 2);
...

DBEntities.AddToListingSet(newListing);
DBEntities.SaveChanges();

In Entity Framework 4 (coming with .NET 4.0) you'll be able to use a simpler syntax more like what you expected.

You can have a look at this article on msdn where you can read more about this!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜