Question

I am working on Entity Data Model and i hv created a method to insert a record into a table of sql server 2005 DB. before inserting record i m chking whether the User with the same name already exist in the table. This is a Class Library and i am refering this in Asp.net web application. When i call this Insert method from web application i m getting exception as "Sequence contains no elements".

When i comment the checkUserExist function, record is inserting into the DB.

Here is my source code.

public class EntityClass
{
    public static string InsertRecord(string username, string domain, string host)
    {
        bool isExist = false;
        bool returnNull = false;
        try
        {

            SolVeEntities entity = new SolVeEntities();
            User ud = new User();

            //before inserting user into the table, verify whether User already exist
            isExist = CheckUserExist(username);

            if (!isExist)
            {
                ud.username = username;
                ud.domain = domain;
                ud.host = host;
                ud.datetime = DateTime.Now;

                entity.Users.AddObject(ud);
                entity.SaveChanges();
            }
            else { returnNull = true;

            }
        }
        catch (Exception ex)
        {

        }

        if (returnNull)
        return "user " + username + " already Exist";
        else
            return username + domain + host;
    }

    private static bool CheckUserExist(string uname)
    {
        bool isExist = false;
        SolVeEntities entity = new SolVeEntities();
        User u1 = entity.Users.First(u => u.username == uname);
        if (u1.username == uname)
        {
            isExist = true;
        }
        else
        { isExist = false; }

        return isExist;
    }
}

Any suggestions/solution pls...thanks. I am getting exception in CheckUserExist method at User u1 = entity.Users.First(u => u.username == uname);

Was it helpful?

Solution

Rewrite CheckUserExist with the following way:

private static bool CheckUserExist(string uname)
{
    using(SolVeEntities entity = new SolVeEntities())
    {
        return entity.Users.Any(u => u.username == uname);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top