我正在尝试创建一个在对象与自身之间具有多对一关系的数据库。 (我有一个用户,用户应该有他知道的其他用户的列表......)
我有两个问题:
代码示例:
(一个国家 - 一个城市 - 为什么在城市阶层中有一个国家对象和一个国家ID?)
[Table]
public class Country
{
private EntitySet<City> citiesRef;
public Country()
{
this.citiesRef = new EntitySet<City>(this.OnCityAdded, this.OnCityRemoved);
}
[Column(IsPrimaryKey = true, IsDbGenerated = true)]
public int ID
{
get;
set;
}
[Column(CanBeNull = false)]
public string Name
{
get;
set;
}
[Association(Name = "FK_Country_Cities", Storage = "citiesRef", ThisKey = "ID", OtherKey = "CountryID")]
public EntitySet<City> Cities
{
get
{
return this.citiesRef;
}
}
private void OnCityAdded(City city)
{
city.Country = this;
}
private void OnCityRemoved(City city)
{
city.Country = null;
}
}
[Table]
public class City
{
private Nullable<int> countryID;
private EntityRef<Country> countryRef = new EntityRef<Country>();
[Column(IsPrimaryKey = true, IsDbGenerated = true)]
public int ID
{
get;
set;
}
[Column(CanBeNull = false)]
public string Name
{
get;
set;
}
[Column(Storage = "countryID", DbType = "Int")]
public int CountryID
{
get
{
return this.countryID;
}
set
{
this.countryID = value;
}
}
[Association(Name = "FK_Country_Cities", Storage = "countryRef", ThisKey = "CountryID", OtherKey = "ID", IsForeignKey = true)]
public Country Country
{
get
{
return this.countryRef.Entity;
}
set
{
Country previousValue = this.countryRef.Entity;
if (((previousValue != value) || (this.countryRef.HasLoadedOrAssignedValue == false)))
{
if ((previousValue != null))
{
this.countryRef.Entity = null;
previousValue.Cities.Remove(this);
}
this.countryRef.Entity = value;
if ((value != null))
{
value.Cities.Add(this);
this.countryID = value.ID;
}
else
{
this.countryID = default(Nullable<int>);
}
}
}
}
}
如何创建我想要的多对一关系(从用户到用户)? 我已经尝试了一些东西而且它不会让我在任何地方..(另外 - 我真的不明白我在那里做什么 - 因为基本上结果是每个用户都有一个id,friendId和一个朋友列表而且我不喜欢我不想要朋友的身份......
[Table]
public class User
{
[Column (IsPrimaryKey=true)]
public int Id { get; set; }
[Column]
public string Name { get; set; }
[Column]
public string Gender { get; set; }
private EntitySet<User> friends;//the list of users the user knows
[Association(Storage = "friends", ThisKey = "Id", OtherKey = "MyFriendId")]
public EntitySet<User> Friends
{
get { return friends; }
set { friends.Assign(value); }
}
public User(int _id, string _name, string _gender)
{
Id = _id;
Name = _name;
Gender = _gender;
Friends = new EntitySet<User>();
}
[Column(CanBeNull = false)]
public int MyFriendId { get; set; }//the other user id
EntityRef<User> myFriend;//the other user object-why??
[Association(Storage = "myFriend", ThisKey = "MyFriendId", OtherKey = "Id", IsForeignKey = true)]
public User MyFriend
{
get
{ return myFriend.Entity; }
set
{ myFriend.Entity = value; }
}
} }
有任何帮助吗? 非常感谢!
答案 0 :(得分:0)
我怀疑你是想要简明扼要。添加第二个表来保存相关用户的商店。
列
ID, IDOfUserWithRelations&amp; RelateduserID
QED。