Cannot use ComboBox SelectedItem as BindingSource for cascaded ComboBox - binding

I have 2 ComboBoxes on my form. I create the bindings as follows:
TestClass myclass = new TestClass("Instruments");
myclass.Add(instr1 = new TestClass("INSTR1"));
myclass.Add(instr2 = new TestClass("INSTR2"));
myclass.Add(instr3 = new TestClass("INSTR3"));
myclass.Add(instr4 = new TestClass("INSTR4"));
instr1.Add(app1 = new TestClass("app1"));
instr1.Add(app2 = new TestClass("app2"));
instr1.Add(app3 = new TestClass("app3"));
instr1.Add(app4 = new TestClass("app4"));
instr2.Add(app5 = new TestClass("app5"));
instr2.Add(app6 = new TestClass("app6"));
instr2.Add(app7 = new TestClass("app7"));
instr2.Add(app8 = new TestClass("app8"));
mysource = new BindingSource(myclass, null);
selectedComboBox1.DataSource = mysource;
selectedComboBox1.DisplayMember = "NAME";
mysource2 = new BindingSource(selectedComboBox1, "SelectedItem");
selectedComboBox2.DataSource = mysource2;
selectedComboBox2.DisplayMember = "NAME";
The class used for the binding looks as follows
class TestClass : BindingList<TestClass>, INotifyPropertyChanged
{
public event RunTestChanged RunTestChangedEventHandler;
public TestClass()
{
this.test = "";
this.name = "";
this.runTest = true;
}
public TestClass(string name)
{
this.test = "";
this.name = name;
this.runTest = true;
}
public TestClass LIST
{
get
{
return this;
}
}
public string NAME
{
get
{
return this.name;
}
set
{
this.name = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("NAME"));
}
}
}
public string TEST
{
get
{
return this.test;
}
set
{
this.test = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("TEST"));
}
}
}
public bool RUNTEST
{
get
{
return runTest;
}
set
{
runTest = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs("RUNTEST"));
}
RunTestArgs myargs = new RunTestArgs(value);
if (RunTestChangedEventHandler != null)
{
RunTestChangedEventHandler(this, myargs);
}
}
}
private bool runTest;
private string name;
private string test;
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
}
when the form first loads the 2 comboboxes are filled as they should be with the expected items. However, if i change an item in selectedComboBox1, the items in selectedComboBox2 aren't updated. I know that I can subscribe to the selectedComboBox1 SelectedIndexChanged event and then rebind the DataSource on selectedComboBox2 and everything will work as expected.
For example:
void selectedComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
mysource2.DataSource = selectedComboBox1.SelectedItem;
mysource2.DataMember = null;
}
Another alternative that works is to perform the databinding as follows:
mysource = new BindingSource(myclass, null);
mysource2 = new BindingSource(mysource, "LIST");
mysource3 = new BindingSource(mysource2, "LIST");
selectedComboBox1.DataSource = mysource;
selectedComboBox1.DisplayMember = "NAME";
selectedComboBox2.DataSource = mysource2;
selectedComboBox2.DisplayMember = "NAME";
However I wanted to know if there was a way to avoid having to subscribe to the event or performing the databinding in a different manner and just have the 2nd ComboBox be updated via the BindingSource using the SelectedItem property. In the end I'm curious to know how to get the BindingSource to be updated via the SelectedItem databinding and if it's not possible what is preventing it from working.
Thank you for your help.

i have the same issue and got resolved by binding Name to SelectedValue of combobox and set ValueMember to be "NAME" property
selectedComboBox1.DisplayMember = "NAME";
selectedComboBox1.ValueMember = "NAME";

Related

JsonSerializer cannot deserialize repeated field in protobuf message

I declared protobuf message like this.
message request {
repeated sint32 Ids = 1;
}
and I tried to save this message in the form of json in DB.
Serialize worked well but when I deserialize it, 'Ids' field is empty.
What am I missing?
var requrest = new Request;
foreach(Int16 Id in Ids) {
request.Ids.Add(Id);
}
string SerializedReq = JsonSerializer.Serialize(request); // "{\"Ids\":[10,28]}"
var DeserializedReq = JsonSerializer.Deserialize<Request>(SerializedReq); // {{}} empty
You should implement a Converter and a ConverterFactory like this:
public class RepeatedFieldConverterFactory : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert)
{
if (!typeToConvert.IsGenericType)
{
return false;
}
if (typeToConvert.GetGenericTypeDefinition() != typeof(RepeatedField<>))
{
return false;
}
return true;
}
public override JsonConverter CreateConverter(
Type type,
JsonSerializerOptions options)
{
Type itemType = type.GetGenericArguments()[0];
JsonConverter converter = (JsonConverter)Activator.CreateInstance(
typeof(RepeatedFieldConverter<>).MakeGenericType(
new Type[] { itemType }),
BindingFlags.Instance | BindingFlags.Public,
binder: null,
args: new object[] { options },
culture: null)!;
return converter;
}
private class RepeatedFieldConverter<TItem> :
JsonConverter<RepeatedField<TItem>>
{
private readonly JsonConverter<TItem> _valueConverter;
private readonly Type _valueType;
public RepeatedFieldConverter(JsonSerializerOptions options)
{
_valueConverter = (JsonConverter<TItem>)options
.GetConverter(typeof(TItem));
_valueType = typeof(TItem);
}
public override RepeatedField<TItem> Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartArray)
{
throw new JsonException();
}
var repeatedField = new RepeatedField<TItem>();
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndArray)
{
return repeatedField;
}
TItem value = _valueConverter.Read(ref reader, _valueType, options)!;
repeatedField.Add(value);
}
throw new JsonException();
}
public override void Write(
Utf8JsonWriter writer,
RepeatedField<TItem> repatedField,
JsonSerializerOptions options)
{
writer.WriteStartArray();
foreach (TItem value in repatedField)
{
_valueConverter.Write(writer, value, options);
}
writer.WriteEndArray();
}
}
}
And use it like this:
var persons = new RepeatedField<Person>();
persons.Add(new Person()
{
Name = "Joe"
});
//Converter for serializing is not mandatory, James Newton-King supports this out of the box ;-)
var jsonPersons = System.Text.Json.JsonSerializer.Serialize(persons, new System.Text.Json.JsonSerializerOptions()
{
Converters = { new RepeatedFieldConverterFactory() }
});
var deserializedPersons = System.Text.Json.JsonSerializer.Deserialize<RepeatedField<Person>>(jsonPersons, new System.Text.Json.JsonSerializerOptions()
{
Converters = { new RepeatedFieldConverterFactory() }
});

How do I programmatically add records to an Umbraco v8 form?

I'm looking to add records to an Umbraco v8 form. I know I need the form guid. Is this how I'd do it? Something like this?
public void PostFormData()
{
Guid FormGuid = new Guid("8494a8f0-94da-490e-bd61-7e658c226142");
var form = _formService.Get(FormGuid);
//place for field data into fieldDic
var fieldDic = new Dictionary<Guid, RecordField>();
var firstName = form.AllFields.First(f => f.Alias == "firstName");
var firstNameRecord = new RecordField(firstName);
firstNameRecord.Values = new List<object>() { "Mad Max" };
fieldDic.Add(firstName.Id, firstNameRecord);
var record = new Record()
{
Created = DateTime.Now,
Form = form.Id,
RecordFields = fieldDic,
State = FormState.Submitted,
};
record.RecordData = record.GenerateRecordDataAsJson();
_recordStorage.InsertRecord(record, form);
}
Here's how I do it. Note, I'm hard-coding the Record.UmbracoPageId to -1 while you might want to actually pass in the correct page ID.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
using Umbraco.Forms.Core.Data.Storage;
using Umbraco.Forms.Core.Models;
using Umbraco.Forms.Core.Persistence.Dtos;
using Umbraco.Forms.Core.Services;
namespace myProject.Services
{
public class FormServiceComposer : IUserComposer
{
public void Compose(Composition composition)
{
composition.Register<IFormService, FormService>(Lifetime.Request);
}
}
public interface IFormService
{
void InsertFormData(Guid formGuid, object formModel, string ipAddress);
}
public class FormService : IFormService
{
private readonly ILogger _logger;
private readonly Umbraco.Forms.Core.Services.IFormService _formService;
private readonly IRecordStorage _recordStorage;
private readonly IRecordFieldStorage _recordFieldStorage;
private readonly IWorkflowService _workflowService;
public FormService(ILogger logger, Umbraco.Forms.Core.Services.IFormService formService, IRecordStorage recordStorage, IRecordFieldStorage recordFieldStorage, IWorkflowService workflowService)
{
_logger = logger;
_formService = formService;
_recordStorage = recordStorage;
_recordFieldStorage = recordFieldStorage;
_workflowService = workflowService;
}
#region IFormService
public void InsertFormData(Guid formGuid, object formModel, string ipAddress)
{
try
{
Form form = _formService.GetForm(formGuid);
Record record = new Record();
foreach (Field field in form.AllFields)
{
string caption = CleanCaption(field.Caption);
if (formModel.GetType().GetProperty(caption) == null) continue;
var propertyValue = formModel.GetType().GetProperty(caption).GetValue(formModel, null);
if (propertyValue != null)
{
List<object> values = ExtractValues(propertyValue);
RecordField recordField = new RecordField
{
Alias = field.Alias,
FieldId = field.Id,
Field = field,
Key = Guid.NewGuid(),
Record = record.Id,
Values = values
};
_recordFieldStorage.InsertRecordField(recordField);
record.RecordFields.Add(recordField.Key, recordField);
}
}
record.Form = formGuid;
record.IP = ipAddress;
record.UmbracoPageId = -1;
record.State = Umbraco.Forms.Core.Enums.FormState.Approved;
record.RecordData = record.GenerateRecordDataAsJson();
_recordStorage.InsertRecord(record, form);
_recordStorage.DisposeIfDisposable();
}
catch (Exception ex)
{
_logger.Error<FormService>(ex, "Failed inserting Umbraco Forms data for {formGuid}");
}
}
#endregion IFormService
#region Private
private string CleanCaption(string caption)
{
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
return rgx.Replace(caption.Trim().Replace(" ", ""), "");
}
private List<object> ExtractValues(object propertyValue)
{
List<object> result = new List<object>();
if (propertyValue is string == false && propertyValue.GetType().GetGenericTypeDefinition() == typeof(List<>))
{
IEnumerable<object> _propertyValue = (IEnumerable<object>)propertyValue;
if (_propertyValue.Any())
{
if (_propertyValue.First().GetType().GetProperties().Count() > 1)
{
JArray _properties = JArray.Parse(JsonConvert.SerializeObject(propertyValue));
foreach (JToken item in _properties)
{
string _value = string.Empty;
foreach (var _property in _propertyValue.First().GetType().GetProperties())
{
string _key = _property.Name;
_value = _value + (_value == "" ? "" : " - ") + item[_key].ToString();
}
result.Add(_value);
}
}
else
{
string _key = _propertyValue.First().GetType().GetProperties().First().Name;
JArray _properties = JArray.Parse(JsonConvert.SerializeObject(propertyValue));
foreach (JToken item in _properties)
{
result.Add(item[_key].ToString());
}
}
}
}
else
{
result.Add(propertyValue);
}
return result;
}
#endregion Private
}
}

How to Inject to EmailMessageService

I'm having problem with injecting my service. I've a ISettingService. I'm testing registration onmy application and using email confirmation.
So, at the EmailMessageService class which is inherit from IIdentityMessageService
I'm using Unity for Ioc. I'd registered ISettingService at unity config like below
.RegisterType<ISettingService, SettingService>()
I need to inject this interface to EmailMessageService class to access settings.
Here is the EmailMessageService class
public class EmailMessagingService : IIdentityMessageService
{
private ISettingService SettingService { get; set; }
public Task SendAsync(IdentityMessage message)
{
var fromEmailAddress = ConfigurationManager
.AppSettings["IdentityFromEmailAddress"];
var text = message.Body;
var html = message.Body;
// Do whatever you want to the message
using (var msg = new MailMessage())
{
msg.From = new MailAddress(fromEmailAddress);
msg.To.Add(new MailAddress(message.Destination));
msg.Subject = message.Subject;
msg.AlternateViews.Add(
AlternateView.CreateAlternateViewFromString(
text, null, MediaTypeNames.Text.Plain)
);
msg.AlternateViews.Add(
AlternateView.CreateAlternateViewFromString(
html, null, MediaTypeNames.Text.Html)
);
// var smtpClient = new SmtpClient("smtp.whatever.net", Convert.ToInt32(587));
// var credentials = new System.Net.NetworkCredential(Keys.EmailUser, Keys.EMailKey);
// smtpClient.Credentials = credentials;
using (var smtpClient = new SmtpClient())
{
var setting = SettingService.Query().Select().FirstOrDefault();
if (setting != null)
{
if (!string.IsNullOrEmpty(setting.SmtpHost))
{
smtpClient.Host = setting.SmtpHost;
smtpClient.Port = Convert.ToInt32(setting.SmtpPort);
if (setting.IsSmtpSsl)
{
smtpClient.EnableSsl = true;
}
}
}
smtpClient.Send(msg);
}
}
return Task.FromResult(0);
}
}
EmailMessageService class instantiating at Startup.Auth
var manager =
new ApplicationUserManager(
new ApplicationUserStore(context.Get<DataContext>()));
...
manager.EmailService = new EmailMessagingService();
I cant use Constructor injecting be cause of this direct call. So i used setter injection. But im getting error like "Object reference not set to an instance of an object"
var setting = SettingService.Query().Select().FirstOrDefault();
in EmailMessageService.
O.K What exacly happend i dont know but by changing UnityMvcActivator Start method like below its fixed.
public static void Start()
{
var container = ContainerManager.GetConfiguredContainer();
UnityConfig.RegisterTypes(container);
FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
try
{
//http://stackoverflow.com/questions/699852/how-to-find-all-the-classes-which-implement-a-given-interface
foreach (var assembly in assemblies)
{
var instances = from t in assembly.GetTypes()
where t.GetInterfaces().Contains(typeof(IDependencyRegister))
&& t.GetConstructor(Type.EmptyTypes) != null
select Activator.CreateInstance(t) as IDependencyRegister;
foreach (var instance in instances.OrderBy(x => x.Order))
{
instance.Register(container);
}
}
}
catch (ReflectionTypeLoadException ex)
{
http://stackoverflow.com/questions/1091853/error-message-unable-to-load-one-or-more-of-the-requested-types-retrieve-the-l
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (Exception exSub in ex.LoaderExceptions)
{
sb.AppendLine(exSub.Message);
System.IO.FileNotFoundException exFileNotFound = exSub as System.IO.FileNotFoundException;
if (exFileNotFound != null)
{
if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
{
sb.AppendLine("Fusion Log:");
sb.AppendLine(exFileNotFound.FusionLog);
}
}
sb.AppendLine();
}
string errorMessage = sb.ToString();
throw new Exception(errorMessage, ex);
//Display or log the error based on your application.
}
// TODO: Uncomment if you want to use PerRequestLifetimeManager
// Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
}

How can I create a task automatically by creating a new workitem in TFS?

I would like to know can I create a new linked task when I create a workitem.
Can anyone give a tip of how to do this?
I've gone through some old code that I previously used for this scenario. The following code creates a linked task whenever a new bug is set to approved.
The code filters to a specific Team Project and uses a specific account to connect. You need to enter these before the plugin will work. You can then modify this code to create the tasks you want.
For a general introduction to server plugins and how to turn the code below into a functioning plugin see Extending Team Foundation
using Microsoft.TeamFoundation.Framework.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.TeamFoundation.Common;
using Microsoft.TeamFoundation.WorkItemTracking.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.Client;
using System.Net;
using System.Collections;
namespace TfsExtension.CreateTaskForBug
{
public class CreateTaskForBugEventHandler : ISubscriber
{
const string projectName = "<Enter your project name here>";
public string Name
{
get
{
return "CreateTaskForBugEventHandler";
}
}
public SubscriberPriority Priority
{
get
{
return SubscriberPriority.Normal;
}
}
public EventNotificationStatus ProcessEvent(
TeamFoundationRequestContext requestContext,
NotificationType notificationType,
object notificationEventArgs,
out int statusCode,
out string statusMessage,
out ExceptionPropertyCollection properties)
{
statusCode = 0;
properties = null;
statusMessage = String.Empty;
try
{
ProcessNotification(notificationType, notificationEventArgs, requestContext);
}
catch (Exception exception)
{
TeamFoundationApplicationCore.LogException("Error processing event", exception);
}
return EventNotificationStatus.ActionPermitted;
}
private static void ProcessNotification(NotificationType notificationType, object notificationEventArgs, TeamFoundationRequestContext requestContext)
{
if (notificationType == NotificationType.Notification && notificationEventArgs is WorkItemChangedEvent)
{
var ev = notificationEventArgs as WorkItemChangedEvent;
if (ev.PortfolioProject == projectName)
{
string workItemType = (from field in ev.CoreFields.StringFields
where field.Name == "Work Item Type"
select field.NewValue).Single();
if (workItemType == "Bug")
{
ProcessBug(ev, requestContext);
}
}
}
}
private static void ProcessBug(WorkItemChangedEvent ev, TeamFoundationRequestContext requestContext)
{
var stateChange = (from field in ev.ChangedFields.StringFields
where field.Name == "State" && field.NewValue == "Approved"
select field).SingleOrDefault();
if (stateChange != null)
{
AddChildTaskToBug(ev, requestContext);
}
}
private static void AddChildTaskToBug(WorkItemChangedEvent ev, TeamFoundationRequestContext requestContext)
{
WorkItemStore wiStore = GetWorkItemStore(requestContext);
WorkItem witem = wiStore.GetWorkItem(ev.CoreFields.IntegerFields[0].NewValue);
Project teamProject = witem.Project;
int bugID = witem.Id;
string bugTitle = witem.Fields["System.Title"].Value.ToString();
string bugAssignedTo = witem.Fields["System.AssignedTo"].Value.ToString();
string bugAreaPath = witem.Fields["System.AreaPath"].Value.ToString();
string bugIterationPath = witem.Fields["System.IterationPath"].Value.ToString();
string bugChangedBy = witem.Fields["System.ChangedBy"].OriginalValue.ToString();
string bugTeamProject = witem.Project.Name;
string childTaskTitle = "Resolve bug " + bugID + " - " + bugTitle;
if (CreateResolutionTask(wiStore, bugID, childTaskTitle))
{
witem = CreateWorkItem(wiStore, teamProject, bugID, bugTitle, bugAssignedTo, bugAreaPath, bugIterationPath);
if (IsValid(witem))
{
witem.Save();
LinkParentAndChild(wiStore, witem, bugID);
}
}
}
private static bool IsValid(WorkItem witem)
{
ArrayList validationErrors = witem.Validate();
return validationErrors.Count == 0;
}
private static void LinkParentAndChild(WorkItemStore wiStore, WorkItem witem, int bugID)
{
var linkType = wiStore.WorkItemLinkTypes[CoreLinkTypeReferenceNames.Hierarchy];
var parentWorkItem = wiStore.GetWorkItem(bugID);
int taskID = witem.Id;
var childWorkItem = wiStore.GetWorkItem(taskID);
parentWorkItem.Links.Add(new WorkItemLink(linkType.ForwardEnd, childWorkItem.Id));
parentWorkItem.Save();
}
private static WorkItem CreateWorkItem(WorkItemStore wiStore, Project teamProject, int bugID, string bugTitle, string bugAssignedTo, string bugAreaPath, string bugIterationPath)
{
WorkItemTypeCollection workItemTypes = wiStore.Projects[teamProject.Name].WorkItemTypes;
WorkItemType wiType = workItemTypes["Task"];
WorkItem witem = new WorkItem(wiType);
witem.Fields["System.Title"].Value = "Resolve bug " + bugID + " - " + bugTitle;
witem.Fields["System.AssignedTo"].Value = bugAssignedTo;
witem.Fields["System.AreaPath"].Value = bugAreaPath;
witem.Fields["System.IterationPath"].Value = bugIterationPath;
witem.Fields["Microsoft.VSTS.Common.Activity"].Value = "Bug Resolution";
return witem;
}
private static bool CreateResolutionTask(WorkItemStore wiStore, int bugID, string childTaskTitle)
{
WorkItem parentBug = wiStore.GetWorkItem(bugID);
WorkItemLinkCollection links = parentBug.WorkItemLinks;
foreach (WorkItemLink wil in links)
{
if (wil.LinkTypeEnd.Name == "Child")
{
WorkItem childTask = wiStore.GetWorkItem(wil.TargetId);
if ((childTask.Title == childTaskTitle) && (childTask.State != "Closed"))
{
return false;
}
}
}
return true;
}
private static Uri GetTFSUri(TeamFoundationRequestContext requestContext)
{
var locationService = requestContext.GetService<TeamFoundationLocationService>();
return new Uri(locationService.GetServerAccessMapping(requestContext).AccessPoint + "/" + requestContext.ServiceHost.Name);
}
private static WorkItemStore GetWorkItemStore(TeamFoundationRequestContext requestContext)
{
NetworkCredential netCred = new NetworkCredential(
"<username>",
"<password>");
WindowsCredential windowsCred = new WindowsCredential(netCred);
var credentials = new TfsClientCredentials(windowsCred);
credentials.AllowInteractive = true;
var tpc = new TfsTeamProjectCollection(
GetTFSUri(requestContext),
credentials);
tpc.Authenticate();
return tpc.GetService<WorkItemStore>();
}
public Type[] SubscribedTypes()
{
return new Type[1] { typeof(WorkItemChangedEvent) };
}
}
}

Delete a context record from grid in kendo UI using LINQ

Hi Im using kendo ui grid in my project.
This is my code to insert records in database.
public static void Insert(StudentViewModel student)
{
student.StudentId = All().OrderByDescending(p => p.StudentId).First().StudentId + 1;
//All().Insert(0, student);
UniRegEntities uniRegEntities = new UniRegEntities();
Student stu =new Student();
stu.FName = student.FirstName;
stu.LName = student.LastName;
stu.Gender = uniRegEntities.Genders.Where(x => x.Title == student.Gender).FirstOrDefault();
stu.Id = student.StudentId;
uniRegEntities.Students.Add(stu);
uniRegEntities.SaveChanges();
}
And this is my update statement.
public static void Update(StudentViewModel student)
{
UniRegEntities context = new UniRegEntities();
var studentToUpdate = context.Students.Where(x => x.Id == student.StudentId).FirstOrDefault();
studentToUpdate.FName = student.FirstName;
studentToUpdate.LName = student.LastName;
studentToUpdate.Gender = context.Genders.Where(x => x.Title == student.Gender).FirstOrDefault();
context.SaveChanges();
}
Anyone can suggest me the delete method?
You can either get an entity from the DB and then delete it or create one and then delete it.
So:
var e = // Get
ctx.DeleteObject(e);
ctx.SaveChanges();
or
var e = new Foo() { FooId = id };
ctx.Entity.Attach(e);
ctx.DeleteObject(e);
ctx.SaveChanges();
Applied to your situation:
You are getting a record so you want to use DeleteObject()
public static void Update(StudentViewModel student)
{
UniRegEntities context = new UniRegEntities();
var studentToDelete = context.Students.Where(x => x.Id == student.StudentId).FirstOrDefault();
context.Students.DeleteObject(studentToUpdate);
context.SaveChanges();
}
context.Students.Remove(context.students.Single(x=>x.Id==student.Id));
Can you please try with below code snippet?
using (var db= new AppContext(ConnectionStr))
{
try
{
con.Configuration.AutoDetectChangesEnabled = false;
var o = new Student { StudentId = student.StudentId };
db.Students.Attach(o);
db.Students.Remove(o);
db.SaveChanges();
}
catch (Exception ex)
{
throw new Exception(ex.InnerException.Message);
}
finally
{
con.Configuration.AutoDetectChangesEnabled = true;
}
}

Resources