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 7092775
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T08:21:23+00:00 2026-05-28T08:21:23+00:00

EDIT: ANSWER AT BOTTOM OF THIS QUESTION Okay so I’ve got some generic EF

  • 0

EDIT: ANSWER AT BOTTOM OF THIS QUESTION

Okay so I’ve got some generic EF functions (most of which I have gotten from here) but they don’t seem to work.

I’ve got 3 classes:

 public class Group : Entity
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public virtual GroupType GroupType { get; set; }

    public virtual ICollection<User> Users { get; set; }
}
 public class GroupType: Entity
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

 public class User: Entity
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string UserName { get; set; }

    public virtual ICollection<Group> Groups { get; set; }
 }

My CRUD Operations:

public void Insert(TClass entity)
    {
        if (_context.Entry(entity).State == EntityState.Detached)
        {
            _context.Set<TClass>().Attach(entity);
        }
        _context.Set<TClass>().Add(entity);
        _context.SaveChanges();
    }

public void Update(TClass entity)
    {
        DbEntityEntry<TClass> oldEntry = _context.Entry(entity);

        if (oldEntry.State == EntityState.Detached)
        {
            _context.Set<TClass>().Attach(oldEntry.Entity);
        }

        oldEntry.CurrentValues.SetValues(entity);
        //oldEntry.State = EntityState.Modified;

        _context.SaveChanges();
    }

public bool Exists(TClass entity)
    {
        bool exists = false;

        if(entity != null)
        {
            DbEntityEntry<TClass> entry = _repository.GetDbEntry(entity);
            exists = entry != null;
        }

        return exists;
    }

public void Save(TClass entity)
    {
        if (entity != null)
        {
            if (Exists(entity))
                _repository.Update(entity);
            else
                _repository.Insert(entity);
        }
    }

Finally I am calling this code in the following method:

public string TestCRUD()
    {

        UserService userService = UserServiceFactory.GetService();
        User user = new User("Test", "Test", "Test", "TestUser") { Groups = new Collection<Group>() };

        userService.Save(user);
        User testUser = userService.GetOne(x => x.UserName == "TestUser");

        GroupTypeService groupTypeService = GroupTypeServiceFactory.GetService();
        GroupType groupType = new GroupType("TestGroupType2", null);

        groupTypeService.Save(groupType);

        GroupService groupService = GroupServiceFactory.GetService();
        Group group = new Group("TestGroup2", null) { GroupType = groupType };
        groupService.Save(group);

        user.Groups.Add(group);
        userService.Save(user);

        return output;
    }

When I get to:

 user.Groups.Add(group);
 userService.Save(user);

I get the following error:

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

With the following inner exception:

The INSERT statement conflicted with the FOREIGN KEY constraint “User_Groups_Source”. The conflict occurred in database “DBNAME”, table “dbo.Users”, column ‘Id’.

The Problems:

1) Exists always returns true even if the entity was just created in memory and therefore insert is never actually being called only Update inside the Save method, I guess this is because I don’t understand DbEntityEntry fully because both itself and Entry.Entity are never null. How can I check for an exists?

2) Even though all the code runs in TestCRUD until the very end, none of those entities are actually being saved to the database. I am positive I have my database set-up correctly because my custom Initializer is dropping and recreating the database always and inserting seed data every time. This is probably because update is always being called as mentioned in number 1.

Any ideas how to fix?

EDIT: ANSWER

As assumed, the problem was Exists was always returning true so insert was never being called. I fixed this by using reflection to get the primary key and inserting that into the find method to get exists like so:

public bool Exists(TClass entity)
    {
        bool exists = false;

        PropertyInfo info  = entity.GetType().GetProperty(GetKeyName());
        if (_context.Set<TClass>().Find(info.GetValue(entity, null)) != null)
            exists = true;

        return exists;
    }

All the other methods started working as expected. However, I got a different error on the same line:

user.Groups.Add(group);
userService.Save(user);

which was:

Violation of PRIMARY KEY constraint ‘PK_GroupTypes_00551192′. Cannot insert duplicate key in object ‘dbo.GroupTypes’.
The statement has been terminated.

I’ll be posting that as a new question since it’s a new error, but it did solve the first problem.

  • 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-28T08:21:24+00:00Added an answer on May 28, 2026 at 8:21 am

    How can I check for an exists?

    The way I’ve typically seen people checking whether an entity already exists is by checking whether its Id property is greater than zero. You should be able to either use an interface with the Id property on it or (if you expect to have Entities with multiple key properties) you could have each entity override an abstract base class, overriding an Exists property to check its own ID properties for non-default values. Or you could use reflection to find the ID property or properties automatically, as explained here.

    I suspect the rest of the issues will go away once you are correctly inserting new items rather than trying to update them.

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

Sidebar

Related Questions

Edit : See my full answer at the bottom of this question. tl;dr answer
EDIT The bare-bones version of this question is, if I have some object o
Edit: I have solved this by myself. See my answer below I have set
EDIT : see bottom First off I searched for an answer before asking this
Edit: From another question I provided an answer that has links to a lot
UPDATE: Solved. Thanks BusyMark! EDIT: This is revised based on the answer below from
EDIT: For anyone coming to this question through searching, you can install a Gnome
Edit: While this question has been asked and answered before ( 1 ), (
EDIT: The answer from @Archer seems to fix this. (please vote him up, because
I have had this question niggling at the curious bit of my mind for

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.