当表有关系时,在edmx文件中的多个表中插入更新

时间:2013-05-18 05:20:49

标签: .net

当表通过实体框架模态(.edmx)在数据库中具有基本派生关系时,如何在多表中插入和更新数据

我正在尝试下面的代码,但它不起作用。

public bool FacilityRegistrationVerification(FacilityRegistration oFacilityRegisteration)
        {       
            {
                using (levytaxEntities context = new levytaxEntities())
                {
                    var cast = context.FacilityRegistrations.Where(x => x.FacilityID == oFacilityRegisteration.FacilityID).Single();
                    cast = oFacilityRegisteration;
                    context.SaveChanges();
                }
           }
        }

1 个答案:

答案 0 :(得分:0)

假设您有两张表Movies& Cast(这两张表的图片如下)---> enter image description here enter image description here

现在你想使用MovieId访问Cast的数据( Cast.MovieId是Movies_tbl.id的FK ) 比Linq还要--->

private static void ShowCast(MoviesEntities moviesEntities)
        {
            using (moviesEntities)
            {
                ShowAllMovies(moviesEntities);

                Console.WriteLine("Movie id");
                var id = Convert.ToInt32(Console.ReadLine());

                using (var mEntities = new MoviesEntities())
                {
                    if (mEntities.Movies_tbl.Any(x => x.id == id))
                    {
                        var Actor = mEntities.Movies_tbl.FirstOrDefault(x => x.id == id).Cast.Actor;
                        Console.WriteLine(Actor);

                        var Actoress = mEntities.Movies_tbl.FirstOrDefault(x => x.id == id).Cast.Actoress;
                        Console.WriteLine(Actoress);
                    }
                }
            }
        }


private static void ShowAllMovies(MoviesEntities moviesEntities)
        {
            Console.WriteLine("movies ids");

            using (moviesEntities)
            {
                var idList = moviesEntities.Movies_tbl.Select(x => x.id);

                foreach (var idin idList )
                {
                    Console.WriteLine(id.ToString());
                }
            }
        }

添加对象(将记录插入数据库) --->

private static void AddMovie(MoviesEntities moviesEntities)
        {
            using (moviesEntities)
            {
                moviesEntities.Movies_tbl.AddObject(new Movies_tbl { title = "ExampleTitle", Cast = new Cast { Actor = "ExampleActor", Actoress = "ExampleActoress" } });
                moviesEntities.SaveChanges();
            }
        }

更新对象(对数据库执行更新操作) --->

private static void UpdateCast(MoviesEntities moviesEntities)
        {
            using (moviesEntities)
            {
                var cast = moviesEntities.Casts.Where(x => x.MovieId == 10).Single();
                cast.Actor = "UpdatedActorName";
                cast.Actoress = "UpdatedActoressName";
                moviesEntities.SaveChanges();
            }
        }

其中MoviesEntities是带有后缀'entities'的部分类,派生自ObjectContext类。

当您通过现有数据库

创建.edmx时,它将自动创建