0

I have 2 tables in my SQL Server. They have a foreign key relationship. I now want to add a new record to the table with the index. For this I want to use the ID of the primary key. I don't know how to write the statement in my C# to add this ID to the record.

I already tried some stuff, but because I'm new to this topic I don't how much sense it makes ^^

e.g.

ArticleId = db.TestArtikel.Where(x => x.Name == "test1")

public static void AnotherFunction()
{
    using (DbEntities db = new DbEntities())
    {
         db.TestProduct.Add(new TestProduct()
            {
                ProductId = Guid.NewGuid(),
                Price = 10,
                DeliveryDate = DateTime.Now,
                ArticleId = 
            });

         db.SaveChanges();
     }
}

When I use the the line above the code for the ArticleId, it throws the error:

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Guid'

2
  • 2
    The error is because your Linq where clause doesn't know it's only returning 1 item. There could be multiple items that match "test1". You should be able to add '.FirstOrDefault()' on the end of that statement to get it work. Commented Aug 2, 2019 at 7:39
  • I'd say, better to use SingleOrDefault(). Commented Aug 2, 2019 at 7:50

2 Answers 2

1

You just need to edit the first query with the below statement and use the ArticleId in add process.

Article = db.TestArtikel.Where(x => x.Name == "test1").SingleOrDefault();


public static void AnotherFunction()
{
 using (DbEntities db = new DbEntities())
 {
     db.TestProduct.Add(new TestProduct()
        {
            ProductId = Guid.NewGuid(),
            Price = 10,
            DeliveryDate = DateTime.Now,
            ArticleId = Article.ArticleId
        });

     db.SaveChanges();
  }
}

The point you should notice it, the Article maybe be null, to prevent the exception you would better to use

Article = db.TestArtikel.Where(x => x.Name == "test1").Single();

Or write a validation statement before adding :

if(Article == null)  //do somthing else 
Sign up to request clarification or add additional context in comments.

Comments

0

Your Where clause don't know how many items that it returns. Try this;

ArticleId = db.TestArtikel.Where(x => x.Name == "test1").FirstOrDefault();

or

ArticleId = db.TestArtikel.Where(x => x.Name == "test1").SingleOrDefault();

it depends your purpose or data.

1 Comment

You can shorten both of these expressions by removing the call to .Where and putting the same lambda in the FirstOrDefault/SingleOrDefault

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.