如何安全地将Entity Framework对象依赖项添加到数据库?

时间:2015-05-17 03:57:44

标签: c# asp.net-mvc entity-framework

我不确定我是否做了一些完全错误的事情,但如果我加入Cinema添加代码,那么电影添加似乎会在天蓝色中加倍(它会覆盖其他电影。 如果在本地运行,它会提供所需的结果。猜猜我需要另一种方法。假设为每个查找/添加创建一个新的数据库上下文将保持一切正确。

// POST: api/ApiMovie
[ResponseType(typeof(Movie))]
public IHttpActionResult PostMovie(Movie movie) {
    MovieRepository movieRepository = new MovieRepository();
    int? movieID = movieRepository.Find(movie, movie.User);
    if (movieID != null)
        return CreatedAtRoute("DefaultApi",
                            new { id = movieID },
                            movie);

    CinemaRepository cinemaRepository = new CinemaRepository();
    int? cinemaID = cinemaRepository.Find(movie.Number, movie.User);
    if (cinemaID == null)
        cinemaID = cinemaRepository.Add(movie.Number, null, movie.User);

    movie.Cinema = (int) cinemaID;
    movieID = movieRepository.Add(movie);

    movie.ID = (int) movieID;
    return CreatedAtRoute("DefaultApi",
                        new { id = movieID },
                        movie);
}





public class MovieRepository
{
    public int? Find(Movie movie, Guid user) {
        DateTime sqlDate = new SqlDateTime(movie.Date).Value;
        String numberTail = Movie.Number.Tail(8);

        using (var db = new ScaffoldingContext()) {
            var found = db.Movies.FirstOrDefault(e => e.Date == sqlDate &&
            e.Number.Contains(numberTail));

            if(found==null)
                return null;

            return found.ID;
        }
    }


    public int Add(Movie movie) {
        using (var db = new ScaffoldingContext()) {
            Movie newMovie = new Movie();
            newMovie.Contact = movie.Contact;
            newMovie.Date = Movie.Date;
            newMovie.Cinema = Movie.Cinema;
            newMovie.User = Movie.User;

            Movie databaseMovie = db.Messages.Add(newMovie);
            db.SaveChanges();
            return databaseMovie.ID;
        }
    }
}






public class CinemaRepository
{
    public int? Find(String number, Guid user) {
        String numberTail = number.Tail(8);
        using (var db = new ScaffoldingContext()) {
            Cinema cinema = db.Cinemas.FirstOrDefault(e => e.Number.Contains(numberTail) &&
            e.User == user);

            if (cinema == null)
                return null;

            return cinema.ID;
        }
    }

    public int Add(string number, Guid? contact, Guid user) {
        using (var db = new ScaffoldingContext()) {
            Cinema cinema = new Cinema();
            cinema.Number = Number;
            cinema.Count = 0;
            cinema.Contact = contact;
            cinema.User = user;
            cinema.Unread = 0;

            Cinema databaseCinema = db.Cinemas.Add(Cinema);
            db.SaveChanges();
            return databaseCinema.ID;
        }
    }
}

0 个答案:

没有答案