Home > Mobile >  How to insert old record to new entity?
How to insert old record to new entity?

Time:03-15

I am trying to check record , if exists declare to data with old one . But if doesnt then create a new one. Here is my code ;

var teamCheck= FootballerDBContext.Teams.Any(r => r.Name == teamName.Text.Trim());

if (teamCheck)
                {
                    team = FootballerDBContext.Teams.FirstOrDefault(c => c.Name == teamName.Text);
                
                }
FootballerDBContext.Teams.Add(team);
FootballerDBContext.SaveChanges(); // throwing exception right there . I did it exactly same to other entity everything was fine. 

Here is other entity , i did the same but Team throws exception. No errors here , doing what i want. It doesnt create new entity with new ID , just declaring old one. ( sponsor has many-to-many relationship , team has one-to-many )

var sponsorCheck = FootballerDBContext.Sponsors.Any(x => x.Name == Sponsor.Text.Trim());
if (sponsorCheck)
                    {
                        sponsor = FootballerDBContext.Sponsors.FirstOrDefault(z => z.Name == Sponsor.Text);
                        
                    }

FootballerDBContext.FootballerSponsor.Add(fbsp);
                        FootballerDBContext.SaveChanges();

CodePudding user response:

Don't do it like you're doing; it queries the database twice

Do a pattern like this instead:

var team = FootballerDBContext.Teams.FirstOrDefault(c => c.Name == teamName.Text.Trim());
            
if(team == default) //or null
{            
    team = new Team(){ Name = teamName.Text };
    FootballerDBContext.Teams.Add(team);
}

team.Location = teamLocation.Text;
...


FootballerDBContext.SaveChanges();
  • Query using Find or FirstOrDefault
  • If the result is null make a new one and assign it to the variable that is null
  • Add the team to the context if you just made a new one
  • Now you definitely have a team, either because you made it new or because it already exists and is looked up
  • You can set other properties
  • Call save changes at the end and an update or insert command will be run as appropriate

CodePudding user response:

These LINQ queries are not the same: teamName.Text.Trim() vs teamName.Text .Trim()

try to check if variable is null or not like this:

string teamName = teamName.Text.Trim()
if (!String.IsNullOrEmpty(teamName)) 
    first: **team** default value is (teamName)
    second: validate linq query... r => r.Name == teamName

if (second == false) 
    save first.
  • Related