. Net EF framework-added, deleted, modified, and queried. netef
Declare an EF context object
Model dbContext = new Model ();
Add operation (insert a data entry to the table)
// Declare the object Contact = new contact () for a table; // Add data Contact to the field in the table. name = "James"; contact. enrollmentDate = DateTime. now; // insert dbContext. contacts. add (contact); // save dbContext. saveChanges ();
Modify (modify table data by ID)
// Declare the object Contact of a table = new contact (); Contact. name = "Zhang sansan"; contact. enrollmentDate = DateTime. now; contact. ID = 3; // This field is required for modification or deletion. // modify dbContext. entry <Contact> (contact ). state = System. data. entity. entityState. modified; // save dbContext. saveChanges ();
Delete (delete table data by ID)
// Delete a piece of data with ID 3 Contact = dbContext. Contacts. Find (3); dbContext. Contacts. Remove (contact); dbContext. SaveChanges ();
Query operations (query all data in a table)
List<Contact> list = dbContext.Contacts.ToList();
Query operation (conditional query)
List <Contact> list = dbContext. Contacts. Where (u => u. Name = "Dongguan"). ToList ();
Query operation (View A single piece of data by ID)
Contact contact = dbContext.Contacts.Find(30);
Create a DbSet object
public partial class Model : DbContext { public Model() : base("name=efdemo") { } public virtual DbSet<Contact> Contacts { get; set; }}
Create a Contact table object
public class Contact { public int ID { get; set; } public string Name { get; set; } public DateTime EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } }