【发布时间】:2015-03-14 05:20:32
【问题描述】:
我有 3 张桌子 人,地址,人地址 人有身份证,姓名 地址有id,地址 personaddress 有 personid,addressid 这是多对多 如果我亲自按名称搜索、删除、更新、添加,所有这些都可以正常工作。与地址相同。但是,我想做的是,当我按名称搜索时,我希望看到它不仅会提取名称,还会提取与该名称关联的所有地址,反之亦然。这就是为什么我有 personaddress 表作为交叉参考。所以这就是我卡住的地方,我不确定如何在 select 上进行连接,因为它需要在所有 3 个表上进行连接。然后删除要求我删除外部参照表和主表。非常感谢任何帮助。
所以我在模型文件夹中创建了人员、地址、人员地址类 人
public class Person
{
public int Id {}
public string Name {}
}
地址
public class Address
{
public int Id {}
public string Address{}
}
个人地址
public class PersonAddress
{
public int PersonId {}
public string AddressId {}
}
我还在 Model 文件夹中创建了 iperson、iaddress、ipersonaddress 类, 接口IPerson
{
IEnumerable<Person> GetAll();
Person Get(int id);
Person Add(Person pers);
void Remove(int id);
bool Update(Person pers);
}
接口地址
{
IEnumerable<Address> GetAll();
AddressGet(int id);
AddressAdd(Address addr);
void Remove(int id);
bool Update(Address addr);
}
接口 IPersonAddress
{
IEnumerable<PersonAddress> GetAll();
PersonAddressGet(int id);
PersonAddressAdd(PersonAddress persaddr);
void Remove(int id);
bool Update(PersonAddress persaddr);
}
然后我在模型文件夹中创建了personrepository、addressrepository、personaddressrepository
public class PersonRepository : IPersonRepository
{
private List<Person> people= new List<Person>();
private int _nextId = 1;
public PersonRepository()
{
Add(new Person{ Name = "Peter Smith" });
Add(new Person{ Name = "Joe Doe" });
}
public IEnumerable<Person> GetAll()
{
return people;
}
public PersonGet(int id)
{
return people.Find(p => p.Id == id);
}
public PersonAdd(Person pers)
{
if (pers== null)
{
throw new ArgumentNullException("pers");
}
pers.Id = _nextId++;
people.Add(pers);
return pers;
}
public void Remove(int id)
{
people.RemoveAll(m => m.Id == id);
}
public bool Update(Person pers)
{
if (pers==null)
{
throw new ArgumentNullException("pers");
}
int index = people.FindIndex(p => p.Id == pers.Id);
if (index ==-1)
{
return false;
}
people.RemoveAt(index);
people.Add(pers);
return true;
}
}
然后我为这 3 个人、地址、个人地址添加了控制器
public class PersonController : ApiController
{
static readonly IPersonRepository repository = new PersonRepository();
public IEnumerable<Person> GetPersonByName(string name)
{
return repository.GetAll().Where(p => p.Name.ToLower().Contains(name.ToLower()));
}
public HttpResponseMessage AddPerson(Person pers)
{
pers= repository.Add(pers);
var response = Request.CreateResponse<Person>(HttpStatusCode.Created, pers);
string uri = Url.Link("DefaultApi", new { id = pers.Id });
response.Headers.Location = new Uri(uri);
return response;
}
public void UpdatePerson(int id, Person person)
{
person.Id = id;
if (!repository.Update(person))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
public void DeletePerson(int id)
{
Person pers= repository.Get(id);
if (pers== null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
repository.Remove(id);
}
}
【问题讨论】:
标签: c# asp.net-mvc-4