2009-01-24 64 views
10

我是一个有点经验的Rails开发人员,我想我会尝试ASP.NET的MVC版本。在这样做,我也决定尝试Linq-> Sql ...Linq To Sql许多许多联接表

我对Linq-> Sql处理连接的方式有点困惑。

我的架构的一个简单的例子是:


ID
标题


ID

books_categories
book_id
CATEGORY_ID

只要这些表拖动到.dbml文件似乎并没有做到这一点。我在Book类books_categories上获得了一个属性,我期望的是一个可以迭代并直接获取Category类的属性。

现在我要做的东西,感觉很不对劲

 foreach (books_categories bc in book.books_categories) 
     { 
      category_names.Add(bc.Category.category.Trim()); 
     } 

[针对接受的答案]
我勉强接受的“写你自己的胶水代码”的答案。在继续我对Linq-> Sql的研究之后,我发现它显然正在慢慢地被放弃以支持(更强大的IMO)实体框架。 EF仍然允许使用LINQ进行查询,并且可以很好地计算出Ruby的ActiveRecord之类的关系。

回答

8

使用部分类实现了图书,并添加适当的方法类别及其特性。使属性前端为Books_Categories属性(您可以使其具有私有可见性,以强制实现您的Categories属性)。

public partial class Books 
{ 
    public IEnumerable<string> CategoryNames 
    { 
     get 
     { 
      return this.Books_Categories 
         .Select(bc => bc.Category.category.Trim()); 
     } 
    } 

    public void AddCategory(Category category) 
    { 
     this.Books_Categories.Add(new Book_Category 
            { 
             Category = category, 
             Book = this 
            }); 
    } 

    public void RemoveCategory(Category category) 
    { 
     var bc = this.Book_Categories 
        .Where(c => c.Category == category) 
        .SingleOrDefault(); 
     this.Books_Categories.Remove(bc); 
    } 
} 

很明显,你需要添加一些错误/边界检查等,但你明白了。

我会告诉你这并不理想,但至少你可以灵活地确定它是如何工作的。

+0

止跌”:

 <p> <label for="CategorySelect">Category:</label> <%= Html.ListBox("CategorySelect") %> <%= Html.ValidationMessage("CategorySelect", "*")%> </p> 
在BooksController中

:在你看来 您只能在添加和删除方法中将Book_Category添加到this.Book_Categories中? – 2009-04-14 16:12:37

+0

编辑错误 - 我可能键入了代码然后重命名属性。将更新。 – tvanfosson 2009-04-14 16:15:20

0

我不认为您的预期结果在Linq to Sql中受支持。

你在做什么可能会觉得不对,但我认为这是解决L2S限制的一种方法。

男人,我真的得让Rails的...

2

实体框架中显式支持多对多映射,但不支持LINQ to SQL。您也可以使用NHibernate等第三方ORM。

0

,如果你想创建一本书,并希望直接到某个类别添加到它,你可以做的是:

 public ActionResult New() 
    { 
      var data = _entities.Categories.ToList(); 
     ViewData["CategorySelect"] = new MultiSelectList(data, "Id", "Name"); 
} 

     [AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult New([Bind(Exclude = "Id")] Book Booknew) 
    { 
     IEnumerable<int> selectedCategories = Request["CategorySelect"].Split(new Char[] { ',' }).Select(idStr => int.Parse(idStr)); 

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

     try { 
      foreach(var item in selectedCategories){ 
       BooksCategories bc = new BooksCategories(); 
       bc.Book = Booknew; 
       bc.CategoryId = item; 
       _entities.BooksCategories.InsertOnSubmit(bc); 
      } 
      _entities.Books.InsertOnSubmit(Booknew); 
      _entities.SubmitChanges();