Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6387785
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T03:11:44+00:00 2026-05-25T03:11:44+00:00

Consider the following scenario: public class Entity1 { virtual public Int32 ID { get;

  • 0

Consider the following scenario:

public class Entity1
{
    virtual public Int32 ID { get; set; }
    [Required]
    virtual public String Name { get; set; }
    [Required]
    virtual public Entity2 ReferenceToEntity2 { get; set; }
}

public class Entity2
{
    virtual public Int32 ID { get; set; }
    [Required]
    virtual public String Name { get; set; }
    virtual public IList<Entity1> ListOfEntity1 { get; set; }
}

[TestClass]
public class EntityFrameworkTests
{
    [TestMethod]
    public void Should_save_entity_with_reference_to_entity_with_required_fields()
    {
        using (var db = new MyContext())
        {
            var entity1 = new Entity1
            {
                Name = "My name",
                ReferenceToEntity2 = new Entity2 { ID = 1 } // reference (Entity2 with ID=1) already exists in the database 
            };
            db.Entity1List.Add(entity1);
            db.SaveChanges(); // exception here
        }
    }

    [TestMethod]
    [ExpectedException(typeof(DbEntityValidationException))]
    public void Should_not_save_empty_entity2_name()
    {
        using (var db = new MyContext())
        {
            var entity2 = new Entity2 { Name = "" };
            db.Entity2List.Add(entity2);
            db.SaveChanges();
        }
    }
}

The first test is not passing. A DbEntityValidationException is raised, referring to the Name property of Entity2 when trying to save Entity1 instance.

I know that I could load entity2 instance by ID and associate it using entity1.ReferenceToEntity2 = db.Entity2List.Find(entity2Id), for example. But I actually have a entity with lots of references, and I don’t want to go to database 10 times only to associate a foreign key!

Is it possible to insert a new entity1 instance into the database relating to an existing entity2 record without having to go to database to retrieve entity2?

Thanks in advance!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T03:11:45+00:00Added an answer on May 25, 2026 at 3:11 am

    Attach is made for such a scenario:

    using (var db = new MyContext())
    {
        var entity1 = new Entity1
        {
            Name = "My name",
            ReferenceToEntity2 = new Entity2 { ID = 1 }
            // reference (Entity2 with ID=1) already exists in the database 
        };
        db.Entity2List.Attach(entity1.ReferenceToEntity2); // must be BEFORE Add
        db.Entity1List.Add(entity1);
        db.SaveChanges();
    }
    

    It tells EF that Entity2 with ID = 1 already exists in the database. The entity is in Unchanged state after Attach and EF won’t send any UPDATE or INSERT statement to the database for this entity. Just the foreign key in entity1 is updated.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Original Question Consider the following scenario: public abstract class Foo { public string Name
consider the following class and struct public class Entity { public IdType Id {get;set;}
Consider following example : public class SomeBusinessLayerService : DataService<MyEntityContainer> { [WebInvoke] void DoSomething(string someParam)
Consider the following two scenarios: //Data Contract public class MyValue { } Scenario 1:
Consider the following code :- public class UsingWait1{ public static void main(String... aaa){ CalculateSeries
Consider I have the following classes: class User { [Key] public Guid Id {get;
Consider following class class test { public: test(int x){ cout<< test \n; } };
Consider the following class structure: class Filter { virtual void filter() = 0; virtual
Consider a following chunk of service: public class ProductService : IProductService { private IProductRepository
Consider the following scenario: element.css({display:'none'}); element.slideDown(1000); // ... // here I want to get

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.