0

I'm working with three tables, but only inserting into two( one called images, and the other an intermediate table). They all have relationships.

Tables:

ProductGroups--
ID
Name

ProductGroup_Images--
ProductGroupID
ImagesID

Images-
ImageID
Path

Could the following code be written more elegantly?

using (StoreDataContext db = new StoreDataContext())
        {                  
            Image img = new Image
            {
                Path = "https://s3.amazonaws.com/mystore/images/public/" + FileUpload1.PostedFile.FileName,    
            };
            db.Images.InsertOnSubmit(img);
            db.SubmitChanges();

            var pg = db.ProductGroups.Where(a => a.Name == txtName.Value).Select(b => b.ID).Single();

            ProductGroups_Image xref = new ProductGroups_Image
            {
                ProductGroupsID = pg,
                ImagesID= img.ImagesID
            };
            db.ProductGroups_Images.InsertOnSubmit(xref);
            db.SubmitChanges();
        }

2 Answers 2

2

Why worry about IDs, when you have referential properties.

Image img = new Image();
img.Path = @"https://s3.amazonaws.com/mystore/images/public/"
  + FileUpload1.PostedFile.FileName;

ProductGroups_Image xref = new ProductGroups_Image();
xref.Image = img;

using (StoreDataContext db = new StoreDataContext())
{
  ProductGroup pg = db.ProductGroups.Where(a => a.Name == txtName.Value).Single();

  xref.ProductGroup = pg;

  db.SubmitChanges();
}
Sign up to request clarification or add additional context in comments.

3 Comments

awesome, I didn't know you could do it like this. Why do examples in books and online show insert examples that are inside the dataContext using statement and use db.tableName.InsertOnsubmit?
Books and online examples usually teach the public contract of DataContext and Table<T>, rather than the subtle object-tracking features.
also what is the @ sign infront of the url string?
0

You can try something like the following...

 ProductGroup temp = db.ProductGroups.Where(a => a.Name == txtName.Value.Select(a).Single();
temp.Images.Add(img);
db.SubmitChanges;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.