Entity framework 4.0 strange with saving data

2019-03-03 19:15发布

问题:

I faced with the next problem. I have a data warehouse with model

public class GameResult
    {
        public int GameResultId { get; set; }

        public virtual Competition Competition { get; set; }
        public virtual CustomDate DateGame { get; set; }       
        public virtual Contender ContenderFirst { get; set; }
        public virtual Contender ContenderSecond { get; set; }
        public virtual Location Location { get; set; }
}



public class Competition
    {
        [Key]
        public int CompetitionId { get; set; }
        public string Name { get; set; }

        //Lazy loading
        public virtual KindSport KindSport { get; set; }


    }

Something like that I generate some data for fact table GameResult

gameResult.Location = location;
gameResult.Competition = competition;
gameResult.ContenderFirst = firstContender;
gameResult.ContenderSecond = secondContender;

public void saveGameResult(GameResult gameResult)
        {
            using (var db = new GameContext())
            {
                db.GameResults.Add(gameResult);
                db.SaveChanges();
            }

        }

But when I try to save data get that I don't save enity just in fact table they getting cascade saved also in child tables as Location, Contender.

How I can solve my problem?

回答1:

Add marks the whole object graph as Added.

This is a way to fix it:

public void saveGameResult(GameResult gameResult, .... more arguments ....)
{
    using (var db = new GameContext())
    {
        db.GameResults.Add(gameResult);
        gameResult.Location = location;
        gameResult.Competition = competition;
        gameResult.ContenderFirst = firstContender;
        gameResult.ContenderSecond = secondContender;
        db.SaveChanges();
    }
}

But then you have to add more arguments.

A more tedious way is to leave everything the way it is and mark each dimension as UnChanged:

db.GameResults.Add(gameResult);
Entry(gameResult.Location).State = EntityState.Unchanged;
...

Yet another way is to set the Id values only:

gameResult.LocationId = location.LocationId;
... etc.

public void saveGameResult(GameResult gameResult)
{
    ... (original code)

But then of course the primitive Id properties should be part of he fact class, forming foreign key assocations.



回答2:

you have to load the entities Location and Contender from the DB. Otherwise they will be inserted in it.