【问题标题】:Inserting into association table (ASP.NET MVC)插入关联表(ASP.NET MVC)
【发布时间】:2011-12-14 17:36:39
【问题描述】:

我正在编写我的第一个 ASP.NET MVC 项目,并且对这个主题非常缺乏经验,所以请多多包涵。

我必须为需要构建的新应用程序使用现有数据库。我已将其设置为数据源,并使用 ADO.NET 实体数据模型来选择我需要的表。我有一张表,其中包含与父记录关联的类别,并由唯一 ID 连接。此表不会出现在设计器中,而是出现在 Associations 文件夹中。如何将记录插入此表?还是我完全错了?

这是我目前的 Create 代码:

//
// POST: /Home/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "KeyID")] KeyDate dateToCreate, int topic, int level, int subject, int audience)
{
    dateToCreate.Created = DateTime.Now;
    dateToCreate.CreatedBy = User.Identity.Name;

    if (!ModelState.IsValid)
        return View();

    keyDateRepository.Add(dateToCreate);
    keyDateRepository.Save();

    return RedirectToAction("Index");
}

这是存储库的代码:

//
// Insert/Delete Methods

public void Add(KeyDate keyDate)
{
   db.KeyDates.AddObject(keyDate);
}

[...]

//
// Persistence

public void Save()
{
    db.SaveChanges();
}

非常感谢任何帮助。

【问题讨论】:

  • 是否需要在创建KeyDate的同时创建关联记录?
  • 嗨,布赖恩。你知道我会怎么做吗?使用 IntelliSense 时,它​​会告诉我其他实体,但不会告诉我相关的实体。
  • 您好,我理解正确,您的意思是如果我有一个用户和角色表,如果它有一个用户角色关联表,将用户链接到角色,您如何更新该表?在 Entity Framework 4 中,这些是直接可用的,但我相信隐藏在 V1 中......所以你使用的是 V1?
  • 是的,这就是我需要做的。看来我正在使用 EF4,所以仍然不确定为什么该表不可用。也许我做错了什么。

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


【解决方案1】:

好吧,我想通了。我没有意识到我需要做的就是将类别添加到该对象的实例中。

dateToCreate.Categories.Add(keyDateRepository.GetCategory(topic));
dateToCreate.Categories.Add(keyDateRepository.GetCategory(level));
dateToCreate.Categories.Add(keyDateRepository.GetCategory(subject));
dateToCreate.Categories.Add(keyDateRepository.GetCategory(audience));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 2012-05-04
    • 2018-09-18
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多