我正在尝试使用来自使用LINQ to Entities的Asp.NET MVC网站的教程,但我决定使用LINQ to SQL。我正处于创建一个名为Groups的新表的位置,该表与Contacts表有关系。从本质上讲,它是一对多关系,其中一个组可以有多个联系人,一个联系人只能有一个组。请参阅下面的CRUD操作示例代码。
我不确定如何在LINQ to SQL中实现它。例如,如何在LINQ to SQL中执行此操作:
return _entities.GroupSet.Include(“Contacts”)。FirstOrDefault();
你应该为两张桌子做一个JOIN还是有另一种方式?
示例代码:
using System.Collections.Generic;
using System.Linq;
using System;
namespace ContactManager.Models
{
public class EntityContactManagerRepository : ContactManager.Models.IContactManagerRepository
{
private ContactManagerDBEntities _entities = new ContactManagerDBEntities();
// Contact methods
public Contact GetContact(int id)
{
return (from c in _entities.ContactSet.Include("Group")
where c.Id == id
select c).FirstOrDefault();
}
public Contact CreateContact(int groupId, Contact contactToCreate)
{
// Associate group with contact
contactToCreate.Group = GetGroup(groupId);
// Save new contact
_entities.AddToContactSet(contactToCreate);
_entities.SaveChanges();
return contactToCreate;
}
public Contact EditContact(int groupId, Contact contactToEdit)
{
// Get original contact
var originalContact = GetContact(contactToEdit.Id);
// Update with new group
originalContact.Group = GetGroup(groupId);
// Save changes
_entities.ApplyPropertyChanges(originalContact.EntityKey.EntitySetName, contactToEdit);
_entities.SaveChanges();
return contactToEdit;
}
public void DeleteContact(Contact contactToDelete)
{
var originalContact = GetContact(contactToDelete.Id);
_entities.DeleteObject(originalContact);
_entities.SaveChanges();
}
public Group CreateGroup(Group groupToCreate)
{
_entities.AddToGroupSet(groupToCreate);
_entities.SaveChanges();
return groupToCreate;
}
// Group Methods
public IEnumerable<Group> ListGroups()
{
return _entities.GroupSet.ToList();
}
public Group GetFirstGroup()
{
return _entities.GroupSet.Include("Contacts").FirstOrDefault();
}
public Group GetGroup(int id)
{
return (from g in _entities.GroupSet.Include("Contacts")
where g.Id == id
select g).FirstOrDefault();
}
public void DeleteGroup(Group groupToDelete)
{
var originalGroup = GetGroup(groupToDelete.Id);
_entities.DeleteObject(originalGroup);
_entities.SaveChanges();
}
}
}
答案 0 :(得分:2)
您需要指定一些DataLoadOptions
来为您创建联接:
为此,您必须使用正确的DataLoadOptions
为每种类型的查询创建一个DataContext:
var db = new WhateverDbDataContext();
DataLoadOptions options = new DataLoadOptions();
db.LoadOptions = options;
options.LoadWith(x => x.Contacts);
return db.SomeTable.FirstorDefault();
答案 1 :(得分:1)
Linq to sql不支持Include方法。如果您不关心这种关系是否延迟加载,那么您不必做任何事情。如果您希望它被急切加载,那么您已经使用了更复杂的DataLoadOptions。
参见这篇文章:
http://blog.stevensanderson.com/2007/12/02/linq-to-sql-lazy-and-eager-loading-hiccups/