. Net EF framework-added, deleted, modified, and queried. netef

Source: Internet
Author: User

. 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; } }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.