1. First create a news table and a news classification table, and establish a primary foreign key relationship as follows:
(Note: When EF is in use, the table needs to define the primary key)
2. Add the entity to the right of the VS2010 project, select to the specified database, in the previous article: http://jianle.blog.51cto.com/429692/723758
(Note: When you add it, you can see that the foreign key attribute of the news entity does not exist, and becomes a navigation property)
3. The method to use when adding foreign keys:
public bool Addnews (string title, int classid, string content,datetime date,int Hot)
{
bool Mark = false;
using (demosmodel.demosentities DDE = new Demosmodel.demosentities ())
{
try
{
var NC = DDE. Newsclass.first (p => p.id = = ClassID);
Demosmodel.news DN = new Demosmodel.news ();
Dn. Newsclass = NC;
Dn. Newstitle = title;
Dn. newscontent = content;
Dn. Newsdate = date;
Dn. Newshot = hot;
Dde. Addtonews (DN);
Dde. SaveChanges ();
Mark = true;
}
catch (Exception err)
{
FileManage.Instance.AddLog (err. message);
}
return mark;
To write to an external health operation, you must first get the corresponding object in the foreign key table:
var NC = DDE. Newsclass.first (p => p.id = = ClassID);
The Newsclass navigation property for the news entity object is then assigned the Foreign key table object that is queried:
Demosmodel.news DN = new Demosmodel.news ();
Dn. Newsclass = NC;
Finally, add the save to:
Dde. Addtonews (DN);
Dde. SaveChanges ();
4. When querying the news table, get the method of the Foreign key table:
Public list<demosmodel.news> newslist ()
{
list<demosmodel.news> List = new list< Demosmodel.news> ();
using (demosmodel.demosentities DDE = new Demosmodel.demosentities ())
{
list = DDE. News.include ("Newsclass"). Tolist<demosmodel.news> ();
}
return list;
}
When querying the news table, you need to include the foreign key table by using the Include method, otherwise the foreign key table navigation property is a null value in the query's results.
Dde. News.include ("Newsclass");