在Asp.Net MVC中保存多对多的关系表

时间:2013-08-05 14:56:23

标签: asp.net-mvc entity-framework

我使用Asp.Net MVC,Entity Framework。我的表格如下所示。

enter image description here

此处,从表格(类型)填充下拉列表。复选框从另一个表(测试)填充。表格如下:

public class Types 
{
    public int TypesID{get;set;}
    public string TestName { get; set; }
    public string TestExplanation { get; set; }
    public int TestTime { get; set; }
}

public class Tests
{
    public int TestID{get;set;
    public string Name { get; set; }
    public string Code { get; set; }
}

public class Types_Tests
{
   public int Types_TestsID{ get; set; }
   public int TypesID { get; set; }
   public int TestsID { get; set; }

   public virtual Types Types { get; set; }
   public virtual Tests Tests { get; set; }
}

Types_test表是类型和测试之间的关系表。当我点击Kaydet按钮时,它会保存类型并检查测试。我使用ViewBag,javascript和hdnvalue进行了此操作。我将检查的checkboz值添加到hdntext。我做了如下保存程序:

[HttpPost]
public ActionResult Index(string drpType, string hdntesttypes)
    {
        var TypeList = Types.GetAll();
        ViewBag.TypesList = new SelectList(TypeList, "Id", "Name");

        var testypeList = testTypes.GetAll();
        ViewBag.TestTypesList = new SelectList(testypeList, "Id", "TestName");


        GenericRepository<TestDisabledTypes> testDisabledRepository = new GenericRepository<TestDisabledTypes>(_context);

        if (!string.IsNullOrEmpty(hdntesttypes))
        {
            string[] disabletypesArray = hdntesttypes.Split(',');

            using (TransactionScope trns = new TransactionScope())
            {

                for (int i = 0; i < disabletypesArray.Length; i++)
                {
                    Test_Types types = new Test_Types ();
                    types.TestTypesID = Convert.ToInt32(disabletypesArray[i]);
                    types.TypesID = Convert.ToInt32(drpType);
                    testDisabledRepository.Insert(types);
                }

                trns.Complete();

            }
        }

        return View();
    }

它吵闹。但我为这个过程寻找更好的解决方案。有人可以给我任何想法吗? 感谢。

2 个答案:

答案 0 :(得分:0)

如果您不需要实体类的其他属性,则不需要创建链接表。 只需定义以下类,EF将自动为您生成链接表。

public class Type 
{
    public int TypesID{get;set;}
    public string TestName { get; set; }
    public string TestExplanation { get; set; }
    public int TestTime { get; set; }
    public ICollection<Test> Tests { get; set; }
}

public class Test
{
    public int TestID{get;set;
    public string Name { get; set; }
    public string Code { get; set; }
    public ICollection<Type> Types {get;set;}
}

答案 1 :(得分:0)

好吧,在EntityFramework中,如果你想创建一个多对多关系对象,你需要创建一个新对象&#34;链接&#34;实体。不幸的是,不可能添加第一个对象,添加第二个对象并说出#34;伙计们,你们处于多对多的关系中。那你感到高兴吗?&#34; :)您需要创建关系对象,在其中设置适当的字段(我认为这些是两个对象本身的ID)并将其添加到模型中的关系集合(实体)。但在此之前,您需要确保包含您要链接的数据的对象已存在于数据库中。否则你会收到错误

此外,无需手动创建交易,因为EF会在您每次获取/保存数据时自动为您执行此操作

相关问题